package com.ysd.lis.service.lab.impl;

import cn.com.jit.ida.util.pki.encoders.Base64;
import cn.com.jit.new_vstk.AdvanceSignClient;
import cn.com.jit.new_vstk.Bean.SymmKeyNo;
import cn.com.jit.new_vstk.Bean.SymmKeyParams;
import cn.com.jit.new_vstk.config.NewConfig;
import cn.com.jit.new_vstk.exception.NewCSSException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bac.BacStainingResult;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bac.BacDrugTestResultMapper;
import com.ysd.lis.mapper.bac.BacObserResultMapper;
import com.ysd.lis.mapper.bac.BacStainingResultMapper;
import com.ysd.lis.mapper.bac.BacTestResultMapper;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethExtParamMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethodMapper;
import com.ysd.lis.request.*;
import com.ysd.lis.request.lab.BatchPrintDto;
import com.ysd.lis.request.lab.BatchPrintVo;
import com.ysd.lis.request.lab.LabMaininfoCreateOrUpdateDto;
import com.ysd.lis.request.lab.UptMainInfoTextChkDoctorDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacStainingResultService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.lis.util.lab.GetLabMainInfoQueryWapper;
import com.ysd.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class LabMainInfoServiceBakImpl extends ServiceImpl<LabItemDictMapper, LabItemDict> {

    private static final Logger logger = LoggerFactory.getLogger(LabMainInfoServiceBakImpl.class);


    @Autowired
    LabReqMainMapper labReqMainMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    LabRptresultMapper labRptresultMapper;

    @Autowired
    LabRptresultImageMapper labRptresultImageMapper;

    @Autowired
    LabRptresultImageService labRptresultImageService;

    @Autowired
    LabRptmainMapper labRptmainMapper;

    @Autowired
    LabRptdetailMapper labRptdetailMapper;

    @Autowired
    PubReportMapper pubReportMapper;

    @Autowired
    PubReportRulesMapper reportRulesMapper;

    @Autowired
    LabRulesVsItemdictMapper rulesVsItemdictMapper;

    @Autowired
    LabReqStateService labReqStateService;

    @Autowired
    LabMainStateService labMainStateService;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    LabReqResultService labReqResultService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    SysParamValueService sysParamValueService;

    @Autowired
    LabTemplateService labTemplateService;

    @Autowired
    LabResultAmendmentMapper labResultAmendmentMapper;

    @Autowired
    LabResultAmendmentService labResultAmendmentService;

    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    LabRptdetailBacService labRptdetailBacService;
    @Autowired
    LabRptdetailStainingService labRptdetailStainingService;
    @Autowired
    LabRptdetailDrugService labRptdetailDrugService;
    @Autowired
    LabRptdetailObserService labRptdetailObserService;

    @Autowired
    SysInterfaceMethodMapper sysInterfaceMethodMapper;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    SysInterfaceMethExtParamMapper sysInterfaceMethExtParamMapper;

    @Autowired
    LabRptresultCalcServiceImpl labRptresultCalcService;
    @Autowired
    LabItemDictMapper labItemDictMapper;
    @Autowired
    PubReportService pubReportService;

    @Autowired
    LabReqMainService labReqMainService;

    @Autowired
    private LabCriticalReportMapper criticalReportMapper;
    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Autowired
    LabMaininfoServiceExtendImpl labMaininfoServiceExtend;

    @Autowired
    LabFeeitemVsItemDictMapper labFeeitemVsItemDictMapper;
    @Autowired
    LabRptBanFeeitemMapper labRptBanFeeitemMapper;
    @Autowired
    LabReqdetailService labReqdetailService;
    @Autowired
    LabFeeItemService labFeeItemService;
    @Autowired
    BacStainingResultService bacStainingResultService;

    public Result getInfo(UptMainInfoTextChkDoctorDto input) throws JsonProcessingException {
        SysUser user = RedisUserManager.getUser();
        logger.info("开始执行审核逻辑");
        UptedLabMainInfo res = new UptedLabMainInfo();
        LambdaUpdateWrapper<LabMaininfo> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(LabMaininfo::getId, BeanUtil.isEmpty(input.getId()) ? "!@#$%" : input.getId());
        LabMaininfo labMaininfo = null;//labMaininfoMapper.selectOne(queryWrapper);
        if (!BeanUtil.isEmpty(input.getId())) {
            labMaininfo = labMaininfoMapper.selectOne(queryWrapper);
        }
        /*初审*/
        if (input.getAction().equals("1") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("初审人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("初审人姓名为空");
            }
            labMaininfo.setFirstChkDoctor(input.getActerCode());
            labMaininfo.setIsChk(new BigDecimal(1));
            labMaininfo.setFirstChkTime(new Timestamp(System.currentTimeMillis()));
            /*走审核逻辑*/
            try {
                labMaininfo = chkLabMainInfo(labMaininfo);
            } catch (Exception e) {
                return Result.fail(e.getMessage().contains(":") ? e.getMessage().split(":")[1] : e.getMessage());
            }
            res.setCurMainInfo(labMaininfo);
        }
        Boolean isChk2 = false;
        /*审核*/
        if (input.getAction().equals("2") && !BeanUtil.isEmpty(labMaininfo)) {
            logger.info("开始审核1111111111");
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }

            labMaininfo.setChkDoctor(input.getActerCode());
            labMaininfo.setChkDoctorNa(input.getActerNa());

            /*走审核逻辑*/
            try {
                labMaininfo = chkLabMainInfo(labMaininfo);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail(e.getMessage().contains(":") ? e.getMessage().split(":")[1] : e.getMessage());
            }
            res.setCurMainInfo(labMaininfo);
            isChk2 = true;
        }
        /*检验*/
        if (input.getAction().equals("3") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            labMaininfo.setTestDoctor(input.getActerCode());
            labMaininfo.setTestDoctorNa(input.getActerNa());
            labMaininfoMapper.updateById(labMaininfo);
            res.setCurMainInfo(labMaininfo);
        }
        if (input.getAction().equals("4") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            labMaininfo.setChkDoctor(input.getActerCode());
            labMaininfo.setChkDoctorNa(input.getActerNa());
            labMaininfoMapper.updateById(labMaininfo);
            res.setCurMainInfo(labMaininfo);
        }
        /*更新其他检验记录相关的人员*/
        if (input.getEdtType() == 2) {
            /*修改所有未审核标本*/
            if (BeanUtil.isEmpty(input.getRptGroup())) {
                return Result.fail("报告单元为空");
            }
            if (BeanUtil.isEmpty(input.getSampleda())) {
                return Result.fail("检验日期为空");
            }

            LabMaininfoPageDto labMaininfoPageDto = new LabMaininfoPageDto();
            labMaininfoPageDto.setRptGroup(input.getRptGroup());
            labMaininfoPageDto.setSampledaBegin(input.getSampleda().toString().substring(0, 10) + " 00:00:00");
            labMaininfoPageDto.setSampledaEnd(input.getSampleda().toString().substring(0, 10) + " 23:59:59");
            MPJLambdaWrapper<LabMaininfo> labMainInfoQueryWapper = GetLabMainInfoQueryWapper.getLabMainInfoQueryWapper(labMaininfoPageDto);
            labMainInfoQueryWapper.and(p -> p.eq(LabMaininfo::getIsChk, new BigDecimal(0)).or().isNull(LabMaininfo::getIsChk));
            List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(labMainInfoQueryWapper);

            //获取数据字典(病人类型、性别、证件类型)
            List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
            List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
            List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();


            for (LabMaininfo itm : labMainInfoList) {
                if (input.getAction().equals("1") || input.getAction().equals("2") || input.getAction().equals("4")) {
                    itm.setChkDoctor(input.getActerCode());
                    itm.setChkDoctorNa(input.getActerNa());
                }
                if (input.getAction().equals("3")) {
                    itm.setTestDoctor(input.getActerCode());
                    itm.setTestDoctorNa(input.getActerNa());
                }
                if (StringUtils.isNotBlank(itm.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                    patTypeList.stream().filter(a -> a.get("code").equals(itm.getPatType())).findFirst().ifPresent(stringObjectMap -> itm.setPatTypeNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(itm.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                    sexList.stream().filter(a -> a.get("code").equals(itm.getSex())).findFirst().ifPresent(stringObjectMap -> itm.setSexNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(itm.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                    idTypeList.stream().filter(a -> a.get("code").equals(itm.getIdType())).findFirst().ifPresent(stringObjectMap -> itm.setIdTypeNa((String) stringObjectMap.get("name")));
                }
            }

            if (!labMainInfoList.isEmpty()) {
                boolean ur = labMaininfoService.updateBatchById(labMainInfoList);
                if (!ur) {
                    //return Result.fail("更新失败");
                    logger.info("更新其他未审核检验记录列表失败");
                }
            }
            res.setUptedLabMainInfos(labMainInfoList);
            res.setCurMainInfo(labMaininfo);

        }
        if (input.getEdtType() == 3) {
            if (StringUtils.isBlank(input.getCodeRange())) {
                return Result.fail("请输入标本号或者标本号范围");
            }
            List<String> codes = GetAimCode(input.getCodeRange());
            if (codes.isEmpty()) {
                return Result.fail("请输入需要修改的标本号范围");
            }

            LabMaininfoPageDto labMaininfoPageDto = new LabMaininfoPageDto();
            labMaininfoPageDto.setRptGroup(input.getRptGroup());
            labMaininfoPageDto.setSampledaBegin(input.getSampleda().toString().substring(0, 10) + " 00:00:00");
            labMaininfoPageDto.setSampledaEnd(input.getSampleda().toString().substring(0, 10) + " 23:59:59");
            MPJLambdaWrapper<LabMaininfo> labMainInfoQueryWapper = GetLabMainInfoQueryWapper.getLabMainInfoQueryWapper(labMaininfoPageDto);
            labMainInfoQueryWapper.and(p -> p.eq(LabMaininfo::getIsChk, new BigDecimal(0)).or().isNull(LabMaininfo::getIsChk));
            labMainInfoQueryWapper.in(LabMaininfo::getSampleNo, codes);
            List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(labMainInfoQueryWapper);

            //获取数据字典(病人类型、性别、证件类型)
            List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
            List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
            List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();


            for (LabMaininfo itm : labMainInfoList) {
                if (input.getAction().equals("1") || input.getAction().equals("2") || input.getAction().equals("4")) {
                    itm.setChkDoctor(input.getActerCode());
                    itm.setChkDoctorNa(input.getActerNa());
                }
                if (input.getAction().equals("3")) {
                    itm.setTestDoctor(input.getActerCode());
                    itm.setTestDoctorNa(input.getActerNa());
                }

                if (StringUtils.isNotBlank(itm.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                    patTypeList.stream().filter(a -> a.get("code").equals(itm.getPatType())).findFirst().ifPresent(stringObjectMap -> itm.setPatTypeNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(itm.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                    sexList.stream().filter(a -> a.get("code").equals(itm.getSex())).findFirst().ifPresent(stringObjectMap -> itm.setSexNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(itm.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                    idTypeList.stream().filter(a -> a.get("code").equals(itm.getIdType())).findFirst().ifPresent(stringObjectMap -> itm.setIdTypeNa((String) stringObjectMap.get("name")));
                }
            }

            if (!labMainInfoList.isEmpty()) {
                boolean ur = labMaininfoService.updateBatchById(labMainInfoList);
                if (!ur) {
                    //return Result.fail("更新失败");
                    logger.info("根据标本号范围更新其他未审核检验记录列表失败");
                }
            }

            res.setUptedLabMainInfos(labMainInfoList);
            res.setCurMainInfo(labMaininfo);
        }
        //同步HIS,只有审核时 才同步报告到HIS
        if (isChk2) {
            LabMaininfo finalLabMaininfo = labMaininfo;
            Map CADataMap = new HashMap();

            CADataMap.put("caUserId", input.getCaUserId());
            CADataMap.put("signDataId", input.getSignDataId());
            StringBuffer dataStr = new StringBuffer();
            dataStr.append(finalLabMaininfo.getPatNo());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getPatNa());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getSex());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getAge());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getPatType());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getReqPurpose());
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getReqNo());
            dataStr.append("|");
            dataStr.append(DateUtil.format(finalLabMaininfo.getSampleda(), "yyyyMMdd"));
            dataStr.append("|");
            dataStr.append(finalLabMaininfo.getSampleNo());
            dataStr.append("结果：");

            MPJLambdaWrapper<LabRptresult> rptresul = new MPJLambdaWrapper<>();
            rptresul.selectAll(LabRptresult.class);
            rptresul.selectAs("itmdict", LabItemDict::getUnit, LabRptresult::getItemUnit);
            rptresul.eq(LabRptresult::getSampleNo, finalLabMaininfo.getSampleNo());
            rptresul.eq(LabRptresult::getRptGroup, finalLabMaininfo.getRptGroup());
            Timestamp startTime1 = Timestamp.valueOf(finalLabMaininfo.getSampleda().toString().substring(0, 10) + " 00:00:00");
            Timestamp endTime1 = Timestamp.valueOf(finalLabMaininfo.getSampleda().toString().substring(0, 10) + " 23:59:59");
            rptresul.ge(LabRptresult::getSampleda, startTime1);
            rptresul.le(LabRptresult::getSampleda, endTime1);
            rptresul.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
            rptresul.eq(LabRptresult::getDelFlag, 0);
            rptresul.orderByAsc(LabItemDict::getSeq);
            List<LabRptresult> labRptresultList = labRptresultMapper.selectList(rptresul);
            for (LabRptresult item11 : labRptresultList) {
                dataStr.append(item11.getItemNo() + item11.getTestResult());
            }
            CADataMap.put("data", dataStr);

            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, labMaininfo.getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

            //优抚ca原始数据签名
            if (StringUtils.isNotBlank(input.getCaTpye()) && input.getCaTpye().equals("1") && StringUtils.isNotBlank(user.getInitializer())) {
                try {
                    AdvanceSignClient client = new AdvanceSignClient("E:\\Limp\\lis_server\\conf\\cssconfig.properties");
                    NewConfig config = client.getConfig();
                    SymmKeyParams symmParams = new SymmKeyNo(config.getTenantId());
                    // 对称加密
                    byte[] endata = client.symmEncrypt(symmParams, dataStr.toString().getBytes());
                    String signResult = new String(Base64.encode(endata));
                    log.error("base64的对称加密结果为：" + signResult);
                    if (StrUtil.isNotEmpty(signResult)) {
                        LabMaininfo labMaininfo1 = new LabMaininfo();
                        labMaininfo1.setId(finalLabMaininfo.getId());
                        labMaininfo1.setSampleda(finalLabMaininfo.getSampleda());
                        labMaininfo1.setCaSignOri(dataStr.toString());
                        labMaininfo1.setCaSignSec(signResult);
                        labMaininfoMapper.updateById(labMaininfo1);
                    }

                } catch (NewCSSException e) {
                    log.error("Ca加密失败错误号为：" + e.getCode());
                    log.error("错误描述为: " + e.getDescription());
                    log.error("日志标识码: " + e.getSerialNumber());
                }
            }

            SysUser sysUser = RedisUserManager.getUser();
            //删除报告
            if (CollectionUtils.isNotEmpty(collect)) {
                try {
                    /*发布报告相关*/
                    for (String webUrl : collect) {
                        //调用HIS接口发布报告HTTP的
//                        String urlHis = webUrl + "/lisRestFul/pushLisReport";
//                        Map<String, Object> hisMap = new HashMap<>();
//                        hisMap.put("id", labMaininfo.getId());
//                        //String s = HttpUtils.doPost(url, JSONUtils.map2json(map));
//                        /*---------------------*/
//                        // 发送请求
//                        String sss = HttpUtil.createPost(urlHis).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(hisMap)).contentType("application/json").execute().body();
//                        logger.info("调用HIS接口返回报文为" + sss);


                        //HL7调用HIS接口发布报告HTTP的
//                        String hl7UrlHis = webUrl + "/PUBLIS_REPORT_TO_HIS";
//                        Map<String, Object> hl7HisMap = new HashMap<>();
//                        hl7HisMap.put("id", labMaininfo.getId());
//                        //String s = HttpUtils.doPost(url, JSONUtils.map2json(map));
//                        /*---------------------*/
//                        // 发送请求
//                        String ssss = HttpUtil.createPost(hl7UrlHis).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(hisMap)).contentType("application/json").execute().body();
//                        logger.info("调用HL7的HIS接口返回报文为" + sss);

                        // 发送请求(如果包含HL7,MQ的取消掉，之前遗留问题，有些人写的不规范)
                        String url = "";
                        if (webUrl.indexOf("MQ") > -1 || webUrl.indexOf("HL7") > -1) {
                            url = webUrl.replace("MQ", "").replace("HL7", "") + "/public/deleteReport";
                        } else {
                            url = webUrl + "/public/deleteReport";
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("rptGroup", labMaininfo.getRptGroup());
                        map.put("sampleNo", labMaininfo.getSampleNo());
                        map.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSampleda()));
                        map.put("orgId", labMaininfo.getOrgId());
                        //String s = HttpUtils.doPost(url, JSONUtils.map2json(map));

                        /*---------------------*/

                        String s = HttpUtil.createPost(url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(map)).contentType("application/json").execute().body();
                        /*---------------------*/

                        //新增报告
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject status = jsonObject.getJSONObject("status");
                        String msg = status.get("msg").toString();
                        String code = status.get("code").toString();
                        if (!"400".equals(code)) {
                            MPJLambdaWrapper<LabRptresult> rptresulWrapper = new MPJLambdaWrapper<>();
                            rptresulWrapper.selectAll(LabRptresult.class);
                            rptresulWrapper.selectAs("itmdict", LabItemDict::getUnit, LabRptresult::getItemUnit);
                            rptresulWrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                            rptresulWrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
                            Timestamp startTime = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 00:00:00");
                            Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 23:59:59");
                            rptresulWrapper.ge(LabRptresult::getSampleda, startTime);
                            rptresulWrapper.le(LabRptresult::getSampleda, endTime);
                            rptresulWrapper.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
                            rptresulWrapper.eq(LabRptresult::getDelFlag, 0);
                            rptresulWrapper.orderByAsc(LabItemDict::getSeq);
                            List<LabRptresult> labRptresults = labRptresultMapper.selectList(rptresulWrapper);
                            if (CollectionUtils.isNotEmpty(labRptresults)) {
                                List<Map> list = new ArrayList<>();
                                Map<String, Object> releaseReportMap = new HashMap<>();
                                //发布报告时的入参，千万不要传mainInfoId,否则后果自负
                                String releaseReport = webUrl + "/public/releaseReport";
                                for (LabRptresult labRptresult : labRptresults) {
                                    HashMap<Object, Object> map1 = new HashMap<>();
                                    map1.put("itemNo", labRptresult.getItemNo());
                                    map1.put("itemNa", labRptresult.getItemNa());
                                    map1.put("unit", labRptresult.getItemUnit());
                                    map1.put("testResult", labRptresult.getTestResult());
                                    map1.put("resultFlag", labRptresult.getResultFlag());
                                    map1.put("ref", StringUtils.isBlank(labRptresult.getRef()) ? "" : labRptresult.getRef());
                                    map1.put("rptGroup", labRptresult.getRptGroup());
                                    map1.put("id", UUID.randomUUID().toString());
                                    map1.put("sampleNo", labMaininfo.getSampleNo());
                                    map1.put("reqNo", labMaininfo.getReqNo());
                                    map1.put("testDoctor", labMaininfo.getTestDoctor());
                                    map1.put("chkDoctor", labMaininfo.getChkDoctor());
                                    map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSampleda()));
                                    list.add(map1);
                                }
                                releaseReportMap.put("orgId", labMaininfo.getOrgId());
                                releaseReportMap.put("username", sysUser.getUsername());
                                releaseReportMap.put("realname", sysUser.getRealname());
                                releaseReportMap.put("reportInfos", list);
                                String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                                //HttpUtils.doPost(releaseReport, JSONUtils.map2json(releaseReportMap));
                                logger.info("发布报告返回值:\n" + release);
                                JSONObject releaseObject = new JSONObject(release);
                                JSONObject releaseStatus = releaseObject.getJSONObject("status");
                                String releaseCode = releaseStatus.get("code").toString();
                                if (!"400".equals(releaseCode)) {
                                    //走存储过程修改
                                    String updateUrl = webUrl + "/public/updateReportStatus";
                                    Map<String, Object> updateMap = new HashMap<>();
                                    updateMap.put("status", "0306");//审核
                                    updateMap.put("reqNo", labMaininfo.getReqNo());
                                    updateMap.put("patType", labMaininfo.getPatType());
                                    updateMap.put("chkDoctor", labMaininfo.getChkDoctor());
                                    updateMap.put("testDoctor", labMaininfo.getTestDoctor());
                                    updateMap.put("patType", labMaininfo.getPatType());
                                    updateMap.put("samplingTime", BeanUtil.isEmpty(labMaininfo.getSamplingTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSamplingTime()));
                                    updateMap.put("signTime", BeanUtil.isEmpty(labMaininfo.getSignTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSignTime()));
                                    updateMap.put("operateTime", BeanUtil.isEmpty(labMaininfo.getTestTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getTestTime()));
                                    updateMap.put("reportTime", BeanUtil.isEmpty(labMaininfo.getChkTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getChkTime()));
                                    updateMap.put("orgId", labMaininfo.getOrgId());
                                    updateMap.put("username", sysUser.getUsername());
                                    updateMap.put("realname", sysUser.getRealname());
                                    updateMap.put("id", labMaininfo.getId());
                                    String update = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                                    logger.info("更新状态返回值:\n" + update);
                                    //HttpUtils.doPost(updateUrl, JSONUtils.map2json(updateMap));
//                                    JSONObject updateObject = new JSONObject(update);
//                                    JSONObject updateStatus = updateObject.getJSONObject("status");
//                                    String updateMsg = updateStatus.get("msg").toString();
//                                    String updateCode = updateStatus.get("code").toString();
//                                    if ("400".equals(updateCode)) {
//                                        return Result.fail(updateMsg);
//                                    }

                                    /*只有出现危急值 才会调用 危急值发布接口*/
                                   /* if (labMaininfo.getIsAlarm() != null && labMaininfo.getIsAlarm().equals(1)) {

                                        MPJLambdaWrapper<LabCriticalReport> lambdaQueryWrapper = new MPJLambdaWrapper<>();
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getId,LabCriticalReportVo::getId);
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getReportPerson,LabCriticalReportVo::getReportPerson);
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getReportTime,LabCriticalReportVo::getReportTime);
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getNotifyPerson,LabCriticalReportVo::getNotifyPerson);
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getSampleNo,LabCriticalReportVo::getSampleNo);
                                        lambdaQueryWrapper.selectAs(LabCriticalReport::getMeasure,LabCriticalReportVo::getMeasure);

                                        lambdaQueryWrapper.selectAs(LabMaininfo::getPatNo,LabCriticalReportVo::getPatNo);
                                        lambdaQueryWrapper.selectAs(LabMaininfo::getPatNa,LabCriticalReportVo::getPatNa);
                                        lambdaQueryWrapper.selectAs(LabMaininfo::getReqDept,LabCriticalReportVo::getReqDept);
                                        lambdaQueryWrapper.selectAs(LabMaininfo::getOrgId,LabCriticalReportVo::getOrgId);
                                        lambdaQueryWrapper.selectAs(LabRptresult::getItemNa,LabCriticalReportVo::getItemNa);
                                        lambdaQueryWrapper.selectAs(LabRptresult::getItemNo,LabCriticalReportVo::getItemNo);
                                        lambdaQueryWrapper.selectAs(LabRptresult::getTestResult,LabCriticalReportVo::getTestResult);
                                        lambdaQueryWrapper.selectAs(LabRptresult::getRef,LabCriticalReportVo::getRef);
                                        lambdaQueryWrapper.selectAs(LabReqMain::getPatId,LabCriticalReportVo::getPatId);


                                        lambdaQueryWrapper.leftJoin(LabMaininfo.class, on->on.eq(LabMaininfo::getRptGroup, LabCriticalReport::getRptGroup).eq(LabMaininfo::getSampleNo,LabCriticalReport::getSampleNo).eq(LabMaininfo::getSampleda,LabCriticalReport::getSampleda));
                                        lambdaQueryWrapper.leftJoin(LabRptresult.class, on->on.eq(LabRptresult::getRptGroup, LabCriticalReport::getRptGroup).eq(LabRptresult::getSampleNo,LabCriticalReport::getSampleNo).eq(LabRptresult::getSampleda,LabCriticalReport::getSampleda));
                                        lambdaQueryWrapper.leftJoin(LabReqMain.class,LabReqMain::getReqNo,LabMaininfo::getReqNo);

                                        lambdaQueryWrapper.eq(LabCriticalReport::getSampleNo, labMaininfo.getSampleNo());
                                        lambdaQueryWrapper.eq(LabCriticalReport::getRptGroup, labMaininfo.getRptGroup());
                                        Timestamp startTime1 = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 00:00:00");
                                        Timestamp endTime1 = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 23:59:59");
                                        lambdaQueryWrapper.ge(LabCriticalReport::getSampleda, startTime1);
                                        lambdaQueryWrapper.le(LabCriticalReport::getSampleda, endTime1);
                                        List<LabCriticalReportVo> criticalReportVos = criticalReportMapper.selectJoinList(LabCriticalReportVo.class, lambdaQueryWrapper);
                                        //获取数据字典(病人类型、性别、证件类型)
                                        List<Map<String, Object>> measureList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("measure").getData();

                                        for (LabCriticalReportVo labCriticalReportVo : criticalReportVos) {

                                            LambdaQueryWrapper<LabCriticalReport> reusltWrapper = new LambdaQueryWrapper<>();

                                            reusltWrapper.eq(LabCriticalReport::getItemNo, labCriticalReportVo.getItemNo());
                                            reusltWrapper.eq(LabCriticalReport::getPatNo, labCriticalReportVo.getPatNo());
                                            List<LabCriticalReport> labCriticalReports1 = criticalReportMapper.selectList(reusltWrapper);
                                            labCriticalReportVo.setNumber(String.valueOf(labCriticalReports1.size()));
                                            if (StringUtils.isNotBlank(labCriticalReportVo.getMeasure()) && CollectionUtils.isNotEmpty(measureList)) {
                                                measureList.stream().filter(a -> a.get("code").equals(labCriticalReportVo.getMeasure())).findFirst().ifPresent(stringObjectMap -> labCriticalReportVo.setMeasure((String) stringObjectMap.get("name")));
                                            }
                                        }
                                        try {
                                            for (LabCriticalReportVo labCriticalReport : criticalReportVos) {
                                                if (StringUtils.isNotBlank(labCriticalReport.getReportTime())) {
                                                    labCriticalReport.setReportTime(labCriticalReport.getReportTime().substring(0, 19));
                                                }
                                                if (StringUtils.isNotBlank(labCriticalReport.getCreateTime())) {
                                                    labCriticalReport.setCreateTime(labCriticalReport.getCreateTime().substring(0, 19));
                                                }
                                                String reportUrl = webUrl + "/pushWjz/pushWjzInterface";
                                                String body = HttpUtil.createPost(reportUrl).body(JSONUtil.toJsonStr(labCriticalReport)).contentType("application/json").execute().body();
                                                JSONObject reportObject = new JSONObject(body);
                                                JSONObject reportStatus = reportObject.getJSONObject("status");
                                                String reportCode = reportStatus.get("code").toString();
                                                if ("400".equals(reportCode)) {
                                                    return Result.fail("接口管理平台异常,请检查");
                                                }
                                            }


                                        } catch (Exception e) {
                                            throw new RuntimeException("接口管理平台异常,请检查");
                                        }
                                    }*/
                                } else {
                                    //调用接口不成功，回退状态
                                    LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                                    lambdaQueryWrapper.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo()).eq(LabRptmain::getSampleda, labMaininfo.getSampleda())
                                            .eq(LabRptmain::getDelFlag, 0);
                                    labRptmainMapper.delete(lambdaQueryWrapper);
                                    labMaininfo.setIsChk(new BigDecimal(0));
                                    labMaininfoService.updateById(labMaininfo);
                                    return Result.fail(msg);
                                }
                            }
                        } else {
                            return Result.fail(msg);
                        }
                    }
                    /*回写过渡板Limp相关，放到线程中，以免影响审核速度，如果同步失败，取消审核，再次审核还会同步一遍*/

                    new Thread(() -> {
                        for (String webUrl : collect) {
                            String url = webUrl + "/public/labMaininfoChk";
//                            String s = HttpUtils.doPost(url, JSONUtils.object2json(finalLabMaininfo));
                            String body = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(finalLabMaininfo)).contentType("application/json").execute().body();
                        }
                    }).start();
                    //山东CA数据加密
                    new Thread(() -> {
                        if (StrUtil.isNotEmpty(input.getJmData())) {
                            LabMaininfo labMaininfo1 = new LabMaininfo();
                            labMaininfo1.setId(finalLabMaininfo.getId());
                            labMaininfo1.setSampleda(finalLabMaininfo.getSampleda());
                            labMaininfo1.setCaSignOri(input.getInitData());
                            labMaininfo1.setCaSignSec(input.getJmData());
                            labMaininfoMapper.updateById(labMaininfo1);
                        }
                    }).start();

                    //数据CA加密
                    new Thread(() -> {

                        for (String webUrl : collect) {
                            if (StringUtils.isNotEmpty(input.getCaUserId()) && StringUtils.isNotEmpty(input.getSignDataId())) {
                                String url = webUrl + "/lisRestFul/getAutoSign";
                                String body = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(CADataMap)).contentType("application/json").execute().body();
                                JSONObject jsonObject = JSONUtil.parseObj(body);
                                String signResult = jsonObject.getJSONObject("data").getStr("signResult");
                                String tsResp = jsonObject.getJSONObject("data").getStr("tsResp");
                                String signCert = jsonObject.getJSONObject("data").getStr("signCert");

                                if (StrUtil.isNotEmpty(signResult)) {
                                    LabMaininfo labMaininfo1 = new LabMaininfo();
                                    labMaininfo1.setId(finalLabMaininfo.getId());
                                    labMaininfo1.setSampleda(finalLabMaininfo.getSampleda());
                                    labMaininfo1.setCaSignOri(dataStr.toString());
                                    labMaininfo1.setCaSignSec(signResult);
                                    labMaininfo1.setCaTimestamp(tsResp);
                                    labMaininfoMapper.updateById(labMaininfo1);
                                }
                            }
                        }
                    }).start();

                } catch (Exception e) {
                    LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo()).eq(LabRptmain::getSampleda, labMaininfo.getSampleda())
                            .eq(LabRptmain::getDelFlag, 0);
                    labRptmainMapper.delete(lambdaQueryWrapper);
                    labMaininfo.setIsChk(new BigDecimal(0));
                    labMaininfoService.updateById(labMaininfo);
                    //throw new RuntimeException("接口管理平台异常,请检查");
                    return Result.fail("接口管理平台异常,请检查");
                }
                return Result.succ(1, "更新成功", res);
            }

        }
        return Result.succ(1, "更新成功", res);
    }

    public Result unChkMainInfo(LabMaininfo labMaininfo) throws RuntimeException {
        //调用api
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, labMaininfo.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        SysUser sysUser = RedisUserManager.getUser();

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {

                    //调用HIS接口发布报告HTTP的
                    String urlHis = webUrl + "/lisRestFul/cancleLisReport";
                    Map<String, Object> hisMap = new HashMap<>();
                    hisMap.put("id", labMaininfo.getId());
                    //String s = HttpUtils.doPost(url, JSONUtils.map2json(map));
                    /*---------------------*/
                    // 发送请求
                    String sss = HttpUtil.createPost(urlHis).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(hisMap)).contentType("application/json").execute().body();
                    logger.info("消审调用HIS接口返回报文为" + sss);


                    //删除报告
                    String url = webUrl + "/public/deleteReport";
                    Map<String, Object> map = new HashMap<>();
                    map.put("rptGroup", labMaininfo.getRptGroup());
                    map.put("sampleNo", labMaininfo.getSampleNo());
                    map.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSampleda()));
                    map.put("orgId", labMaininfo.getOrgId());
//                    String s = HttpUtils.doPost(url, JSONUtils.map2json(map));

                    String s = HttpUtil.createPost(url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(map)).contentType("application/json").execute().body();

                    //新增报告
//                    JSONObject jsonObject = new JSONObject(s);
//                    JSONObject status = jsonObject.getJSONObject("status");
//                    String msg = status.get("msg").toString();
//                    String code = status.get("code").toString();
//                    if ("400".equals(code)) {
//                        return Result.fail("接口管理平台异常,请检查");
//                    }
                }

                /*回写过渡板Limp相关，放到线程中，以免影响取消审核速度，如果同步失败，取消审核，再次审核还会同步一遍*/
                new Thread(() -> {
                    for (String webUrl : collect) {
                        String url = webUrl + "/public/labMaininfoUnChk";
                        String body = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(labMaininfo)).contentType("application/json").execute().body();
                    }
                }).start();
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.succ(1, "取消审核成功", labMaininfo);
    }

    public Result unChkBatchMainInfo(List<LabMaininfo> labMaininfo) throws RuntimeException {
        //调用api
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, labMaininfo.get(0).getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {

                    //删除报告
                    String url = webUrl + "/public/unChkBatch";
                    Map<String, Object> map = new HashMap<>();
                    map.put("list", labMaininfo);

                    String s = HttpUtils.doPost(url, JSONUtil.toJsonStr(map));
                    //新增报告
                    JSONObject jsonObject = new JSONObject(s);
                    JSONObject status = jsonObject.getJSONObject("status");
                    String msg = status.get("msg").toString();
                    String code = status.get("code").toString();
                    if ("400".equals(code)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }

                /*回写过渡板Limp相关，放到线程中，以免影响取消审核速度，如果同步失败，取消审核，再次审核还会同步一遍*/
                new Thread(() -> {
                    for (String webUrl : collect) {
                        for (LabMaininfo maininfo : labMaininfo) {
                            String url = webUrl + "/public/labMaininfoUnChk";
                            String body = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(maininfo)).contentType("application/json").execute().body();
                        }
                    }
                }).start();
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.succ(1, "取消审核成功", labMaininfo);
    }

    /**
     * 检验记录审核逻辑
     *
     * @param mainInfo
     */
    public LabMaininfo chkLabMainInfo(LabMaininfo mainInfo) {
        try {
            /*检验结果小于0时禁止审核 jyjgxy0sjzsh*/
            String p2Str = "";
            SysParamParam sysp2 = new SysParamParam();
            List<SysParamFieldValueDto> kcflrdstndtmLst = null;
            try {
                /*sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("jyjgxy0sjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                p2Str = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgxy0sjzsh", mainInfo.getRptGroup(), null);
                p2Str = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }

            /*上机记录无条码号禁止审核 sjjlNoReqNoJzsj*/
            String sjjlNoReqNoJzsj = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "sjjlNoReqNoJzsj", mainInfo.getRptGroup(), null);
                sjjlNoReqNoJzsj = paramResult.getValueStr();
                logger.info("上机记录无条码号时redis的值："+sjjlNoReqNoJzsj);
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*上机记录无条码号时,禁止审核*/
            logger.info("上机记录无条码号时,禁止审核系统参数为："+sjjlNoReqNoJzsj);
            if(ToolsUtils.isNotEmpty(sjjlNoReqNoJzsj)&&sjjlNoReqNoJzsj.equals("1")){
                if(ToolsUtils.isEmpty(mainInfo.getReqNo())){
                    throw new RuntimeException("上机记录无条码号时,禁止审核");
                }
            }

            /*检验结果为空时禁止审核 jyjgwksjzsh*/
            String jyjgwksjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgwksjzsh", mainInfo.getRptGroup(), null);
                jyjgwksjzsh = paramResult.getValueStr();
                logger.info("检验结果为空时redis的值："+jyjgwksjzsh);
//                if(StrUtil.isEmpty(jyjgwksjzsh)) {
//                    sysp2 = new SysParamParam();
//                    sysp2.setParamCode("bgdyxtcs");
//                    sysp2.setField("jyjgwksjzsh");
//                    sysp2.setClassifyCode(mainInfo.getRptGroup());
//                    kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
//                    jyjgwksjzsh = kcflrdstndtmLst.get(0).getValue();
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            /*无检验医生禁止审核 wjyysjzsh*/
            String wjyysjzsh = "";
            try {
                /*sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("wjyysjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                wjyysjzsh = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wjyysjzsh", mainInfo.getRptGroup(), null);
                wjyysjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*无审核医生禁止审核 wshysjzsh*/
            String wshysjzsh = "";
            try {
                /*sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("wshysjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                wshysjzsh = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wshysjzsh", mainInfo.getRptGroup(), null);
                wshysjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*检验、审核医生相同禁止审核 jyysshysxtjzsh*/
            String jyysshysxtjzsh = "";
            try {
                /*sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("jyysshysxtjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                jyysshysxtjzsh = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyysshysxtjzsh", mainInfo.getRptGroup(), null);
                jyysshysxtjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*检验结果包含以下值时禁止审核(,分隔) jyjgbhyxzsjzsh*/
            String jyjgbhyxzsjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgbhyxzsjzsh", mainInfo.getRptGroup(), null);
                jyjgbhyxzsjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*无病人姓名禁止审核 wbrxmjzsh*/
            String wbrxmjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wbrxmjzsh", mainInfo.getRptGroup(), null);
                wbrxmjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
            //_labrptresultmapper.eq(LabRptresult::getMaininfoId, mainInfo.getId());
            Timestamp timestamp = new Timestamp(mainInfo.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            _labrptresultmapper.ge(LabRptresult::getSampleda, startTime);
            _labrptresultmapper.le(LabRptresult::getSampleda, endTime);
            _labrptresultmapper.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
            _labrptresultmapper.eq(LabRptresult::getSampleNo, mainInfo.getSampleNo());
            _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
            List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
            /*检验结果小于0,禁止审核*/
            if (StringUtils.isNotBlank(p2Str) && p2Str.equals("1")) {
                boolean islezero = false;
                for (LabRptresult m : rptresultlist) {
                    try {
                        BigDecimal res = new BigDecimal(m.getTestResult());
                        if (BeanUtil.isEmpty(res) && res.compareTo(new BigDecimal(0)) < 0) {
                            islezero = true;
                            break;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (islezero) {
                    throw new RuntimeException("检验结果小于0,禁止审核");
                }
            }
            /*检验结果为空时,禁止审核*/
            logger.info("检验结果为空时,禁止审核系统参数为："+jyjgwksjzsh);
            if (StringUtils.isNotBlank(jyjgwksjzsh) && jyjgwksjzsh.equals("1")) {
                if (CollectionUtils.isEmpty(rptresultlist)) {
                    throw new RuntimeException("检验结果为空时,禁止审核");
                }
                boolean isempty = false;
                for (LabRptresult m : rptresultlist) {
                    try {
                        if (StrUtil.isEmpty(m.getTestResult())) {
                            isempty = true;
                            break;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (isempty) {
                    throw new RuntimeException("检验结果为空时,禁止审核");
                }
            }
            /*无检验医生,禁止审核*/
            if (StringUtils.isNotBlank(wjyysjzsh) && wjyysjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getTestDoctor())) {
                    throw new RuntimeException("无检验医生,禁止审核");
                }
            }
            /*无审核医生禁止审核*/
            if (StringUtils.isNotBlank(wshysjzsh) && wshysjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getChkDoctor())) {
                    throw new RuntimeException("无审核医生,禁止审核");
                }
            }
            /*检验、审核医生相同禁止审核*/
            if (StringUtils.isNotBlank(jyysshysxtjzsh) && jyysshysxtjzsh.equals("1")) {
                if (!BeanUtil.isEmpty(mainInfo.getChkDoctor()) && !BeanUtil.isEmpty(mainInfo.getTestDoctor()) && mainInfo.getChkDoctor().equals(mainInfo.getTestDoctor())) {
                    throw new RuntimeException("检验、审核医生相同,禁止审核");
                }
            }
            /*检验结果包含以下值时禁止审核(,分隔)*/
            if (StringUtils.isNotBlank(jyjgbhyxzsjzsh) && !jyjgbhyxzsjzsh.equals("")) {
                boolean iscontains = false;
                String[] cns = jyjgbhyxzsjzsh.contains(",") ? jyjgbhyxzsjzsh.split(",") : new String[]{jyjgbhyxzsjzsh};
                for (LabRptresult m : rptresultlist) {
                    try {
                        for (String mm : cns) {
                            if (!BeanUtil.isEmpty(m.getTestResult()) && m.getTestResult().contains(mm)) {
                                iscontains = true;
                                break;
                            }
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (iscontains) {
                    throw new RuntimeException("检验结果包含以下值时禁止审核,禁止审核," + jyjgbhyxzsjzsh);
                }
            }
            /*无病人姓名禁止审核*/
            if (StringUtils.isNotBlank(wbrxmjzsh) && wbrxmjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getPatNa())) {
                    throw new RuntimeException("无病人姓名,禁止审核");
                }
            }

            /*重新计算检验结果*/
            //labRptresultService.reCalcRptRssults(mainInfo);

            mainInfo.setIsChk(new BigDecimal(2));

            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "shsblysfkshsj", mainInfo.getRptGroup(), null);
                logger.info("paramResult:" + paramResult);
                String shsblysfkshsjStr = paramResult.getValueStr();

                if (StringUtils.isNotEmpty(shsblysfkshsjStr) && shsblysfkshsjStr.equals("1") && !BeanUtil.isEmpty(mainInfo.getChkTime())) {
                    //保留原始非空审核时间，不做处理
                } else {
                    mainInfo.setChkTime(new Timestamp(System.currentTimeMillis()));
                }
            } catch (Exception e) {
                logger.info("保留原始非空审核时间eee:" + e.getMessage());
                mainInfo.setChkTime(new Timestamp(System.currentTimeMillis()));
            }

            int i = labMaininfoMapper.updateById(mainInfo);
            if (i <= 0) {
                return null;
            }

            try {
                MPJLambdaWrapper<LabItemDict> queryWrapper1 = new MPJLambdaWrapper<>();
                queryWrapper1.distinct().selectAll(LabItemDict.class).selectAs("fee", LabFeeItem::getFeeCode, LabItemDict::getFeeItemCode).selectAs("fee", LabFeeItem::getFeeName, LabItemDict::getFeeItemName).leftJoin(LabFeeitemVsItemDict.class, "dict", p -> p.eq(LabFeeitemVsItemDict::getItemNo, LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getRptGroup, LabItemDict::getRptGroup)).leftJoin(LabFeeItem.class, "fee", p -> p.eq(LabFeeItem::getId, LabFeeitemVsItemDict::getFeeItemId)).leftJoin(LabReqdetail.class, "detail", p -> p.eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode)).eq(LabItemDict::getDelFlag, 0).eq(LabFeeitemVsItemDict::getDelFlag, 0).eq(LabFeeItem::getDelFlag, 0).eq(LabReqdetail::getDelFlag, 0).eq(LabFeeitemVsItemDict::getRptGroup, mainInfo.getRptGroup()).eq(LabReqdetail::getReqNo, mainInfo.getReqNo());
                List<LabItemDict> itemDictList = labItemDictMapper.selectList(queryWrapper1);
                if (CollectionUtils.isNotEmpty(itemDictList)) {
                    //查询出当前检测结果
                    LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    //lambdaQueryWrapper.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
                    lambdaQueryWrapper.ge(LabRptresult::getSampleda, startTime);
                    lambdaQueryWrapper.le(LabRptresult::getSampleda, endTime);
                    lambdaQueryWrapper.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
                    lambdaQueryWrapper.eq(LabRptresult::getSampleNo, mainInfo.getSampleNo());
                    lambdaQueryWrapper.eq(LabRptresult::getDelFlag, 0);
                    List<LabRptresult> labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);
                    if (CollectionUtils.isNotEmpty(labRptresults)) {
                        labRptresults.forEach(a -> {
                            Optional<LabItemDict> first = itemDictList.stream().filter(p -> p.getItemNo().equals(a.getItemNo())).findFirst();
                            if (first.isPresent()) {
                                a.setFeeCode(first.get().getFeeCode());
                                a.setFeeName(first.get().getFeeItemName());
                                labRptresultMapper.updateById(a);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*审核后生成状态记录*/
            /*标本流程状态记录*/
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(mainInfo.getId());
                reqState1.setStateCode("100");//mainInfo.getIsChk().toString());
                String txt = "";
                if (mainInfo.getIsChk().equals(new BigDecimal(1))) {
                    reqState1.setStateCode("99");
                    txt = "初审";
                }
                if (mainInfo.getIsChk().equals(new BigDecimal(2))) {
                    txt = "审核";
                }
                reqState1.setStateValue(txt + "状态");
                reqState1.setCreator(mainInfo.getChkDoctor());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
                labMainStateService.save(reqState1);

                if (StringUtils.isNotBlank(mainInfo.getReqNo())) {
                    /*标本状态*/
                    LabReqMain rmEntry = this.getLabReqMainEntity(mainInfo.getReqNo());
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                    reqState.setSampleda(mainInfo.getSampleda());
                    reqState.setSampleNo(mainInfo.getSampleNo());
                    reqState.setRptGroup(mainInfo.getRptGroup());
                    reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setStateCode("100");
                    reqState.setStateValue("标本" + txt);
                    reqState.setOrgId(mainInfo.getOrgId());
                    reqState.setCreator(sysUser.getId());
                    String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + txt + ",标本号:" + (BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setRemark(rmk);
                    reqState.setSeq(labReqStateService.getMaxCount(mainInfo.getReqNo()));
                    labReqStateService.save(reqState);

                    if (BeanUtil.isNotEmpty(rmEntry)) {
                        rmEntry.setState("100");
                        rmEntry.setStateNa("标本" + txt);
                        labReqMainService.saveOrUpdate(rmEntry);
                        //--根据报告单元和reqno 删除数据后再添加
                        String rptGroup = mainInfo.getRptGroup();
                        String reqNo = rmEntry.getReqNo();

                        LambdaQueryWrapper<LabReqResult> delReqResultWrapper = new LambdaQueryWrapper<>();
                        delReqResultWrapper.eq(LabReqResult::getReqNo, reqNo).eq(LabReqResult::getRptGroup, rptGroup);
                        labReqResultService.remove(delReqResultWrapper);
                        if (CollectionUtils.isNotEmpty(rptresultlist)) {
                            List<LabReqResult> addReqResultList = new ArrayList<>();

                            for (LabRptresult rptresult : rptresultlist) {
                                LabReqResult addReqResult = new LabReqResult();
                                BeanUtil.copyProperties(rptresult, addReqResult, "id");
                                addReqResult.setReqNo(reqNo);
                                addReqResultList.add(addReqResult);
                            }
                            labReqResultService.saveBatch(addReqResultList);
                        }

                    }
                }
            }).start();

            /*审核后,先删除已有报告记录，再生成报告记录*/
            try {
                Result r = previewRpt(mainInfo, 1);
            } catch (Exception exception) {
                log.error("maininfoId:" + mainInfo.getId());
                log.error("审核后生成报告记录异常:", exception);
                exception.printStackTrace();
            }

            /*更新申请表，使信息同步*/
//            try {
//                MPJLambdaWrapper<LabReqMain> queryReqmainWrapper = new MPJLambdaWrapper<>();
//                queryReqmainWrapper.selectAll(LabReqMain.class).selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa).eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, mainInfo.getReqNo()).leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType);
//                LabReqMain reqMain = labReqMainMapper.selectOne(queryReqmainWrapper);
//                BeanUtil.copyProperties(mainInfo, reqMain, "id", "isPrint", "createTime", "editTime", "delFlag", "creator", "editor");
//                labReqMainMapper.updateById(reqMain);
//            } catch (Exception ex) {
//                //TODO
//            }

            return mainInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //    @Transactional(rollbackFor = Exception.class)
    public Result previewRpt(LabMaininfo labMaininfo, int printFlag) {
        if (ToolsUtils.isEmpty(labMaininfo)) {
            return Result.fail("入参异常！");
        }
        //根据报告单元获取模版codeR
        MPJLambdaWrapper<PubReportRules> reportRulesWrapper = new MPJLambdaWrapper<>();
        reportRulesWrapper.selectAll(PubReportRules.class).selectAs(PubReport::getName, PubReportRules::getReportName).leftJoin(PubReport.class, PubReport::getId, PubReportRules::getReportId).eq(PubReportRules::getDelFlag, 0).eq(PubReportRules::getRptGroup, labMaininfo.getRptGroup()).orderByAsc(PubReportRules::getRuleType).orderByAsc(PubReportRules::getPriorityLevel);

        List<PubReportRules> reportRules = reportRulesMapper.selectList(reportRulesWrapper);
        if (ToolsUtils.isEmpty(reportRules) || reportRules.size() == 0) {
            return Result.fail("根据报告单元未获取到报告模版！");
        }

        List<String> pubReportIds = reportRules.stream().map(p -> p.getReportCode()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(pubReportIds)) {
            return Result.fail("根据报告单元规则未获取到报告模版！");
        }
        // List<LabRptresult> collect = reportRules.stream().filter(la -> ToolsUtils.isEmpty(la.getFeeCode())).collect(Collectors.toList());
        //Map<String, List<PubReportRules>> collect = reportRules.stream().collect(Collectors.groupingBy(PubReportRules::getType));
        //collect1.put("", collect);


        int i = 0;
        String mainInfoId = labMaininfo.getId();//检验记录主键
        LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptmain::getDelFlag, 0);
        //queryWrapper.eq(LabRptmain::getMainInfoId, mainInfoId);//123cfz
        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(LabRptmain::getSampleda, startTime);
        queryWrapper.le(LabRptmain::getSampleda, endTime);
        queryWrapper.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper.eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo());
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(LabRptmain::getOrgId, sysUser.getOrgId());
        }
        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapper);

        LabMaininfo labMaininfo1 = labMaininfoMapper.selectById(mainInfoId);
        ReportPreviewDto reportPreviewDto;
        List<ReportPreviewDto> reportPreviewDtos = new ArrayList<>();
        if ("2".equals(labMaininfo1.getIsChk().toString()) && CollectionUtils.isNotEmpty(labRptmainList) && printFlag == 2) {
            for (LabRptmain labRptmain : labRptmainList) {
                reportPreviewDto = new ReportPreviewDto();
                reportPreviewDto.setId(labRptmain.getId());
                reportPreviewDto.setIsChecked(true);
                reportPreviewDto.setReportId(labRptmain.getRptTemplateCode());
                reportPreviewDto.setReportTemplateName(pubReportMapper.selectById(labRptmain.getRptTemplateCode()).getName());
                reportPreviewDtos.add(reportPreviewDto);
            }
            return Result.succ(1, "成功", reportPreviewDtos);
        }
        if (ToolsUtils.isNotEmpty(labRptmainList)) {
            for (LabRptmain labRptmain : labRptmainList) {
                LambdaQueryWrapper<LabRptdetail> delLabRptdetailWrapper = new LambdaQueryWrapper<>();
                delLabRptdetailWrapper.eq(LabRptdetail::getRptMainCode, labRptmain.getRptCode());
                labRptdetailMapper.delete(delLabRptdetailWrapper);
                labRptmainMapper.deleteById(labRptmain.getId());
            }
        }


        LambdaQueryWrapper<PubReport> queryPubReportWrapper = new LambdaQueryWrapper<>();
        queryPubReportWrapper.eq(PubReport::getDelFlag, 0);
        queryPubReportWrapper.in(PubReport::getId, pubReportIds);
        List<PubReport> pubReports = pubReportMapper.selectList(queryPubReportWrapper);
        //根基检验信息查询结果信息
        LambdaQueryWrapper<LabRptresult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabRptresult::getDelFlag, 0);
        //wrapper.eq(LabRptresult::getMaininfoId, labMaininfo.getId());
        wrapper.ge(LabRptresult::getSampleda, startTime);
        wrapper.le(LabRptresult::getSampleda, endTime);
        wrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
        wrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
        List<LabRptresult> rptresultList = labRptresultMapper.selectList(wrapper);

        //特殊报告判断写入reportPreviewDtos
        List<LabRptresult> equalList;
        List<LabRptresult> notEqualList;
        LabRptmain labRptmain;
        labMaininfoServiceExtend.specialLabRptHandle(reportRules, rptresultList, reportPreviewDtos, labMaininfo);
        //若预览中数据则展示特殊报告
        if (reportPreviewDtos.size() > 0) {
            labRptmain = new LabRptmain();
            labRptmain.setOrgId(labRptmain.getOrgId());
            labRptmain.setMainInfoId(labMaininfo.getId());
            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
            labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
            labRptmain.setSampleda(labMaininfo.getSampleda());
            labRptmain.setSampleNo(labMaininfo.getSampleNo());
            labRptmain.setRptTemplateCode(reportPreviewDtos.get(0).getReportId());
            labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
            labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
            labRptmain.setIsExported(0);

            List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(rptEntries)) {
                labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
            }

            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
            i = labRptmainMapper.insert(labRptmain);
            return Result.succ("成功");
        }


        PubReportRules pubReportRulesEntry = reportRules.get(reportRules.size() - 1);
        if (ToolsUtils.isEmpty(pubReportRulesEntry)) {
            return Result.fail("查不到报告模板规则");
        }
        String ruleType = pubReportRulesEntry.getRuleType();

        if (Objects.equals(ruleType, "4")) {
            LambdaQueryWrapper<LabRulesVsItemdict> queryWrapperVS = new LambdaQueryWrapper<>();
            queryWrapperVS.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(reportRules.size() - 1).getId()).eq(LabRulesVsItemdict::getType, "1");
            List<LabRulesVsItemdict> rulesVsItemdicts = rulesVsItemdictMapper.selectList(queryWrapperVS);
            if (rulesVsItemdicts.size() > 0) {
                boolean isAnyContained = rptresultList.stream().anyMatch(rule -> rulesVsItemdicts.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));
                //满足拆分条件，则存储报告信息
                if (isAnyContained && "1".equals(pubReportRulesEntry.getIsSplit())) {
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(sysUser.getOrgId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(reportRules.size() - 1).getReportId());
                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                    labRptmain.setIsExported(0);
                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        //找到与rulesVsItemdicts中的itemDictCode相等的记录
                        equalList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().anyMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List
                        if (ToolsUtils.isNotEmpty(equalList)) {
                            for (LabRptresult labRptresult : equalList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(sysUser.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                    }
                    //返回报告预览需要的数据 [{id:'1',isChecked:true,reportObjectCode:'XXXXX生化报告'},{id:'2',isChecked:false,reportObjectCode:'XXXXX免疫报告'}]

                    reportPreviewDto = new ReportPreviewDto();
                    // reportPreviewDto.setId(labRptmain.getId());
                    reportPreviewDto.setIsChecked(false);
                    reportPreviewDto.setReportId(reportRules.get(reportRules.size() - 1).getReportId());
                    reportPreviewDto.setReportTemplateName(reportRules.get(reportRules.size() - 1).getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                }

                //不拆分，且满足规则四，按规则四生成报告，其他规则不再使用
                if (isAnyContained && !"1".equals(pubReportRulesEntry.getIsSplit())) {
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(sysUser.getOrgId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(reportRules.size() - 1).getReportId());
                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                    labRptmain.setIsExported(0);
                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        //找到与rulesVsItemdicts中的itemDictCode相等的记录
                        equalList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().anyMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List
                        if (ToolsUtils.isNotEmpty(equalList)) {
                            for (LabRptresult labRptresult : equalList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(sysUser.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                    }
                    //返回报告预览需要的数据 [{id:'1',isChecked:true,reportObjectCode:'XXXXX生化报告'},{id:'2',isChecked:false,reportObjectCode:'XXXXX免疫报告'}]

                    reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setIsChecked(true);
                    reportPreviewDto.setReportId(pubReportRulesEntry.getReportId());
                    reportPreviewDto.setReportTemplateName(pubReportRulesEntry.getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                    return Result.succ(1, "预览成功", reportPreviewDtos);
                }

                //找到与rulesVsItemdicts中的itemDictCode不相等的记录
                notEqualList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().noneMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List

                /*检验结果中不再除了规则四中的数据  不再有其他项目部署，则不再进行生成报告*/
                if (ToolsUtils.isEmpty(notEqualList) || notEqualList.size() <= 0) {
                    return Result.succ(1, "预览成功", reportPreviewDtos);
                }

                int size = reportRules.size() - 2;
                if (size < 0) {
                    return Result.fail("没有找到报表,请维护报表后重试");
                }
                String ruleType1 = reportRules.get(size).getRuleType();
                switch (ruleType1) {
                    case "3":
                        if (notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(sysUser.getOrgId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                            labRptmain.setPublishDoctorNa(sysUser.getRealname());
                            labRptmain.setIsExported(0);
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(sysUser.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            // reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        } else {

                            size = reportRules.size() - 3;
                            if (size < 0) {
                                return Result.fail("没有找到报表,请维护报表后重试");
                            }
                            String ruleType2 = reportRules.get(size).getRuleType();
                            if (Objects.equals(ruleType2, "2")) {
                                LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                                queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                                List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                                boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));

                                if (anyMatch || notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                    labRptmain = new LabRptmain();
                                    labRptmain.setOrgId(sysUser.getOrgId());
                                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                    labRptmain.setMainInfoId(labMaininfo.getId());
                                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                                    labRptmain.setSampleda(labMaininfo.getSampleda());
                                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                                    labRptmain.setIsExported(0);
                                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                    i = labRptmainMapper.insert(labRptmain);
                                    //插入LAB_RPTDETAIL表
                                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                                        if (ToolsUtils.isNotEmpty(notEqualList)) {
                                            for (LabRptresult labRptresult : notEqualList) {
                                                LabRptdetail rptdetail = new LabRptdetail();
                                                rptdetail.setOrgId(sysUser.getOrgId());
                                                rptdetail.setRptMainCode(labRptmain.getId());
                                                rptdetail.setRptResultId(labRptresult.getId());
                                                i = labRptdetailMapper.insert(rptdetail);
                                            }
                                        }
                                    }
                                    reportPreviewDto = new ReportPreviewDto();
                                    // reportPreviewDto.setId(labRptmain.getId());
                                    reportPreviewDto.setIsChecked(true);
                                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                    reportPreviewDtos.add(reportPreviewDto);
                                } else {
                                    size = reportRules.size() - 4;
                                    if (size < 0) {
                                        return Result.fail("没有找到报表,请维护报表后重试");
                                    }

                                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                    labRptmain = new LabRptmain();
                                    labRptmain.setOrgId(sysUser.getOrgId());
                                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                    labRptmain.setMainInfoId(labMaininfo.getId());
                                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                                    labRptmain.setSampleda(labMaininfo.getSampleda());
                                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                                    labRptmain.setIsExported(0);
                                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                    i = labRptmainMapper.insert(labRptmain);
                                    //插入LAB_RPTDETAIL表
                                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                                        if (ToolsUtils.isNotEmpty(notEqualList)) {
                                            for (LabRptresult labRptresult : notEqualList) {
                                                LabRptdetail rptdetail = new LabRptdetail();
                                                rptdetail.setOrgId(sysUser.getOrgId());
                                                rptdetail.setRptMainCode(labRptmain.getId());
                                                rptdetail.setRptResultId(labRptresult.getId());
                                                i = labRptdetailMapper.insert(rptdetail);
                                            }
                                        }
                                    }
                                    reportPreviewDto = new ReportPreviewDto();
                                    // reportPreviewDto.setId(labRptmain.getId());
                                    reportPreviewDto.setIsChecked(true);
                                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                    reportPreviewDtos.add(reportPreviewDto);
                                }
                            }
                        }
                        break;
                    case "2":
                        LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                        List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                        boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));

                        if (anyMatch || notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(sysUser.getOrgId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                            labRptmain.setPublishDoctorNa(sysUser.getRealname());
                            labRptmain.setIsExported(0);
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(sysUser.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            // reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        } else {
                            size = reportRules.size() - 3;
                            if (size < 0) {
                                return Result.fail("没有找到报表,请维护报表后重试");
                            }

                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(sysUser.getOrgId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                            labRptmain.setPublishDoctorNa(sysUser.getRealname());
                            labRptmain.setIsExported(0);
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(sysUser.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            // reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        }
                        break;
                    default:
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(sysUser.getOrgId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                        labRptmain.setPublishDoctorNa(sysUser.getRealname());
                        labRptmain.setIsExported(0);
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            if (ToolsUtils.isNotEmpty(notEqualList)) {
                                for (LabRptresult labRptresult : notEqualList) {
                                    LabRptdetail rptdetail = new LabRptdetail();
                                    rptdetail.setOrgId(sysUser.getOrgId());
                                    rptdetail.setRptMainCode(labRptmain.getId());
                                    rptdetail.setRptResultId(labRptresult.getId());
                                    i = labRptdetailMapper.insert(rptdetail);
                                }
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        // reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                        break;
                }
                return Result.succ(1, "预览成功", reportPreviewDtos);
            }

        } else {
            int size = reportRules.size() - 1;
            if (size < 0) {
                return Result.fail("查找报表失败,请维护后重试");
            }
            String ruleType1 = reportRules.get(size).getRuleType();
            switch (ruleType1) {
                case "3":
                    if (rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(sysUser.getOrgId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                        labRptmain.setPublishDoctorNa(sysUser.getRealname());
                        labRptmain.setIsExported(0);
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(sysUser.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        // reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    } else {
                        size = reportRules.size() - 2;
                        if (size < 0) {
                            return Result.fail("查找报表失败,请维护后重试");
                        }
                        ruleType1 = reportRules.get(size).getRuleType();
                        if (Objects.equals(ruleType1, "2")) {
                            LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                            queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                            List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                            boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));


                            if (anyMatch || rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                                //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                labRptmain = new LabRptmain();
                                labRptmain.setOrgId(sysUser.getOrgId());
                                labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                labRptmain.setMainInfoId(labMaininfo.getId());
                                labRptmain.setRptGroup(labMaininfo.getRptGroup());
                                labRptmain.setSampleda(labMaininfo.getSampleda());
                                labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                                labRptmain.setPublishDoctorNa(sysUser.getRealname());
                                labRptmain.setIsExported(0);
                                labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                i = labRptmainMapper.insert(labRptmain);
                                //插入LAB_RPTDETAIL表
                                if (ToolsUtils.isNotEmpty(rptresultList)) {
                                    for (LabRptresult labRptresult : rptresultList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(sysUser.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                                reportPreviewDto = new ReportPreviewDto();
                                // reportPreviewDto.setId(labRptmain.getId());
                                reportPreviewDto.setIsChecked(true);
                                reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                reportPreviewDtos.add(reportPreviewDto);
                            } else {
                                size = reportRules.size() - 3;
                                if (size < 0) {
                                    return Result.fail("查找报表失败,请维护后重试");
                                }
                                //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                labRptmain = new LabRptmain();
                                labRptmain.setOrgId(sysUser.getOrgId());
                                labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                labRptmain.setMainInfoId(labMaininfo.getId());
                                labRptmain.setRptGroup(labMaininfo.getRptGroup());
                                labRptmain.setSampleda(labMaininfo.getSampleda());
                                labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                                labRptmain.setPublishDoctorNa(sysUser.getRealname());
                                labRptmain.setIsExported(0);
                                labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                i = labRptmainMapper.insert(labRptmain);
                                //插入LAB_RPTDETAIL表
                                if (ToolsUtils.isNotEmpty(rptresultList)) {
                                    for (LabRptresult labRptresult : rptresultList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(sysUser.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                                reportPreviewDto = new ReportPreviewDto();
                                // reportPreviewDto.setId(labRptmain.getId());
                                reportPreviewDto.setIsChecked(true);
                                reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                reportPreviewDtos.add(reportPreviewDto);
                            }
                        }
                    }
                    break;
                case "2":
                    LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                    List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                    boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));


                    if (anyMatch || rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(sysUser.getOrgId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                        labRptmain.setPublishDoctorNa(sysUser.getRealname());
                        labRptmain.setIsExported(0);
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(sysUser.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        // reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    } else {
                        size = reportRules.size() - 2;
                        if (size < 0) {
                            return Result.fail("查找报表失败,请维护后重试");
                        }
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(sysUser.getOrgId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                        labRptmain.setPublishDoctorNa(sysUser.getRealname());
                        labRptmain.setIsExported(0);
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(sysUser.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        // reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    }
                    break;
                default:
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(sysUser.getOrgId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                    labRptmain.setIsExported(0);
                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        for (LabRptresult labRptresult : rptresultList) {
                            LabRptdetail rptdetail = new LabRptdetail();
                            rptdetail.setOrgId(sysUser.getOrgId());
                            rptdetail.setRptMainCode(labRptmain.getId());
                            rptdetail.setRptResultId(labRptresult.getId());
                            i = labRptdetailMapper.insert(rptdetail);
                        }
                    }
                    reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setId(labRptmain.getId());
                    reportPreviewDto.setIsChecked(true);
                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                    break;
            }
        }

        //  reportPreviewDto.set
        if (i > 0) {
            return Result.succ(1, "成功", reportPreviewDtos);
        } else {
            return Result.fail("预览数据失败！");
        }
    }

    /*调用接口返回申请信息*/
    public Result getApiReqMainInfo(AddLabMaininfo labReqMain) {
        /*调接口*/
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);
        SysUser sysUser = RedisUserManager.getUser();
        LabReqMain q = new LabReqMain();
        q.setReqNo(labReqMain.getReqNo());
        q.setOrgId(orgId);
        q.setUsername(sysUser.getUsername());
        q.setRealname(sysUser.getRealname());

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());//

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    String returnMsg = HttpUtil.createPost(webUrl + "/public/SyncReqMain").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().sync().body();
                    JSONObject jsonObject = new JSONObject(returnMsg);
                    JSONObject status = jsonObject.getJSONObject("status");
                    String code = status.get("code").toString();
                    if ("400".equals(code)) {
                        return Result.fail(jsonObject.getStr("data"));
                    } else {
                        //调用移动护理的接口插入到申请表中
                        String body = HttpUtil.createPost(webUrl + "/public/SyncYdhlCollectInfo").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().sync().body();
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.succ(200, "有数据，同步成功", null);
    }


    public Result findHistoryResultByLabMaininfo(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.succ(1, "id为空", "");
        }
        LambdaQueryWrapper<LabMaininfo> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfo::getDelFlag, 0);
        queryMI.eq(LabMaininfo::getId, id);
        LabMaininfo miEntry = labMaininfoMapper.selectOne(queryMI);
        if (BeanUtil.isEmpty(miEntry)) {
            return Result.succ(1, "查无上机记录", "");
        }

        LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptresult::getSampleda, miEntry.getSampleda()).eq(LabRptresult::getRptGroup, miEntry.getRptGroup()).eq(LabRptresult::getSampleNo, miEntry.getSampleNo()).eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);
        //添加历史结果记录近3次
        //查询本次所有项目
        List<String> collect = labRptresults.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());
        //查询出该病人最近五次本次检测所有结果的的结果
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        lambdaQueryWrappers.eq(LabMaininfo::getRptGroup, miEntry.getRptGroup()).eq(LabMaininfo::getPatNa, miEntry.getPatNa()).eq(LabMaininfo::getIdNo, miEntry.getIdNo()).isNotNull(LabMaininfo::getIdNo).isNotNull(LabMaininfo::getPatNa).eq(LabMaininfo::getDelFlag, 0).lt(LabMaininfo::getSampleda, miEntry.getSampleda()).orderByDesc(LabMaininfo::getSampleda);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(lambdaQueryWrappers);

        if (CollectionUtils.isNotEmpty(labMaininfos) && labMaininfos.size() > 3) {
            labMaininfos = labMaininfos.subList(0, 3);
        }

        List<Map> historyList = new ArrayList<>();
        try {
            for (LabMaininfo labMaininfo : labMaininfos) {
                Map historyMap = new HashMap();
                //便利这个人的历史检测结果
                LambdaQueryWrapper<LabRptresult> resultQueryWrapper = new LambdaQueryWrapper<>();
                resultQueryWrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup()).in(LabRptresult::getItemNo, collect).eq(LabRptresult::getDelFlag, 0).eq(LabRptresult::getSampleda, labMaininfo.getSampleda());
                List<LabRptresult> labRptresults1 = labRptresultMapper.selectList(resultQueryWrapper);
                List<LabRptresult> list = new ArrayList<>();
                labRptresults.forEach(a -> {
                    Optional<LabRptresult> first = labRptresults1.stream().filter(p -> p.getItemNo().equals(a.getItemNo())).findFirst();
                    if (first.isPresent()) {
                        if (StringUtils.isNotEmpty(first.get().getTestResult())) {
                            list.add(first.get());
                        }
                    }
                });
                if (CollectionUtils.isNotEmpty(list)) {
                    historyMap.put("historyDate", labMaininfo.getSampleda().toString().substring(0, 10));
                    historyMap.put("data", list);
                    historyList.add(historyMap);
                }
            }
        } catch (Exception e) {
            log.error("获取历史数据异常");
        }

        return Result.succ(1, "查询结果成功", historyList);
    }


    public Result findHistoryResultByLabMaininfo1(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.succ(1, "id为空", "");
        }
        LambdaQueryWrapper<LabMaininfo> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfo::getDelFlag, 0);
        queryMI.eq(LabMaininfo::getId, id);
        LabMaininfo miEntry = labMaininfoMapper.selectOne(queryMI);
        if (BeanUtil.isEmpty(miEntry)) {
            return Result.succ(1, "查无上机记录", "");
        }

        LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //lambdaQueryWrapper.eq(LabRptresult::getSampleda, miEntry.getSampleda());
        Timestamp timestamp = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        lambdaQueryWrapper.ge(LabRptresult::getSampleda, startTime);
        lambdaQueryWrapper.le(LabRptresult::getSampleda, endTime);
        lambdaQueryWrapper.eq(LabRptresult::getRptGroup, miEntry.getRptGroup());
        lambdaQueryWrapper.eq(LabRptresult::getSampleNo, miEntry.getSampleNo());
        lambdaQueryWrapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);
        //添加历史结果记录近3次
        //查询本次所有项目
        List<String> collect = labRptresults.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());
        //查询出该病人最近五次本次检测所有结果的的结果

        /*结果比较根据【报告单元系统选项】*/
        SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(miEntry.getOrgId(), "jgbjyj", miEntry.getRptGroup(), null);
        SysParamSearchOutputDto rptGroupResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(miEntry.getOrgId(), "jgbjyqlb", miEntry.getRptGroup(), null);
        String jgbjyj = ToolsUtils.isEmpty(paramResult) ? "" : paramResult.getValueStr();
        String rptGroups = (ToolsUtils.isEmpty(rptGroupResult)||("null").equals(rptGroupResult.getValueStr())) ? "[]" : rptGroupResult.getValueStr();
        JSONArray jsonArray = new JSONArray(rptGroups);
        List<String> rptGroupList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            rptGroupList.add(jsonArray.getString(i));
        }
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        //lambdaQueryWrappers.eq(LabMaininfo::getRptGroup, miEntry.getRptGroup());
        if(ToolsUtils.isNotEmpty(jgbjyj)){
            lambdaQueryWrappers.eq("0".equals(jgbjyj), LabMaininfo::getPatNa, miEntry.getPatNa());
            lambdaQueryWrappers.eq("1".equals(jgbjyj), LabMaininfo::getPatNo, miEntry.getPatNo());
            lambdaQueryWrappers.eq("2".equals(jgbjyj), LabMaininfo::getPatNa, miEntry.getPatNa());
            lambdaQueryWrappers.eq("2".equals(jgbjyj), LabMaininfo::getPatNo, miEntry.getPatNo());
            lambdaQueryWrappers.eq("3".equals(jgbjyj), LabMaininfo::getIdNo, miEntry.getIdNo());
        }else {
            lambdaQueryWrappers.eq(LabMaininfo::getPatNa, miEntry.getPatNa());
            lambdaQueryWrappers.eq(LabMaininfo::getIdNo, miEntry.getIdNo());
            lambdaQueryWrappers.isNotNull(LabMaininfo::getIdNo);
            lambdaQueryWrappers.isNotNull(LabMaininfo::getPatNa);
            lambdaQueryWrappers.ne(LabMaininfo::getIdNo, "");
            lambdaQueryWrappers.ne(LabMaininfo::getPatNa, "");
        }
        //根据系统参数 查询报告单元
        if (CollectionUtils.isNotEmpty(rptGroupList)) {
            lambdaQueryWrappers.in(LabMaininfo::getRptGroup, rptGroupList);
        } else {
            lambdaQueryWrappers.eq(LabMaininfo::getRptGroup, miEntry.getRptGroup());
        }
        lambdaQueryWrappers.eq(LabMaininfo::getDelFlag, 0);
        lambdaQueryWrappers.lt(LabMaininfo::getSampleda, miEntry.getSampleda());
        lambdaQueryWrappers.orderByDesc(LabMaininfo::getSampleda);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(lambdaQueryWrappers);

        if (CollectionUtils.isNotEmpty(labMaininfos) && labMaininfos.size() > 3) {
            labMaininfos = labMaininfos.subList(0, 3);
        }

        List<Map> historyList = new ArrayList<>();
        try {
            for (LabMaininfo labMaininfo : labMaininfos) {
                Map historyMap = new HashMap();
                //便利这个人的历史检测结果
                LambdaQueryWrapper<LabRptresult> resultQueryWrapper = new LambdaQueryWrapper<>();
                resultQueryWrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
                resultQueryWrapper.in(LabRptresult::getItemNo, collect);
                resultQueryWrapper.eq(LabRptresult::getDelFlag, 0);
                //resultQueryWrapper.eq(LabRptresult::getSampleda, labMaininfo.getSampleda());
                timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                formattedDate = sdf.format(timestamp);
                startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
                resultQueryWrapper.ge(LabRptresult::getSampleda, startTime);
                resultQueryWrapper.le(LabRptresult::getSampleda, endTime);
                resultQueryWrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                List<LabRptresult> labRptresults1 = labRptresultMapper.selectList(resultQueryWrapper);
                List<LabRptresult> list = new ArrayList<>();
                labRptresults.forEach(a -> {
                    Optional<LabRptresult> first = labRptresults1.stream().filter(p -> p.getItemNo().equals(a.getItemNo())).findFirst();
                    if (first.isPresent()) {
                        if (StringUtils.isNotEmpty(first.get().getTestResult())) {
                            list.add(first.get());
                        }
                    }
                });
                if (CollectionUtils.isNotEmpty(list)) {
                    historyMap.put("historyDate", labMaininfo.getSampleda().toString().substring(0, 10));
                    historyMap.put("data", list);
                    historyList.add(historyMap);
                }
            }
        } catch (Exception e) {
            log.error("获取历史数据异常");
        }

        return Result.succ(1, "查询结果成功", historyList);
    }


    public LabReqMain getLabReqMainEntity(String reqno) {
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class)
                .selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa)
                .leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType)
                .eq(LabReqMain::getDelFlag, 0)
                .eq(LabReqMain::getReqNo, reqno);
        queryWrapper.orderByDesc(LabReqMain::getCreateTime);
        List<LabReqMain> reqMains = labReqMainMapper.selectList(queryWrapper);

        return reqMains.isEmpty() ? null : reqMains.get(0);
    }

    /**
     * 通过id获取关联的部门和数据字典信息
     *
     * @param id
     * @return
     */
    public LabMaininfo getMainInfoById(String id) {
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, LabMaininfo::getReqDept);
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", SysUser::getUsername, LabMaininfo::getTestDoctor);
        queryWrapper.leftJoin(SysUser.class, "chk", SysUser::getUsername, LabMaininfo::getChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "rechk", SysUser::getUsername, LabMaininfo::getReChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "prt", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        queryWrapper.leftJoin(SysUser.class, "sampl", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        queryWrapper.leftJoin(SysUser.class, "signer", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        queryWrapper.eq(LabMaininfo::getId, id);

        queryWrapper.orderByAsc(LabMaininfo::getSampleNo);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }
        if (CollectionUtils.isNotEmpty(labMaininfos)) {
            return labMaininfos.get(0);
        } else {
            return new LabMaininfo();
        }
    }


    /*更新季铵盐记录
     * t:1 检验记录同步申请信息相同字段
     * t:2
     */
    public Result updateMaininfoController(LabMaininfoCreateOrUpdateDto input, Integer t) throws JsonProcessingException {
        if (StringUtils.isBlank(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (StringUtils.isBlank(input.getSampleNo())) {
            return Result.fail("标本号为空");
        }
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(input.getLabMaininfo())) {
            return Result.fail("检验记录为空");
        }
        if (StringUtils.isNotBlank(input.getLabMaininfo().getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(input.getLabMaininfo().getPatNa());
            input.getLabMaininfo().setPatPyName(apply);
        }
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);

        queryWrapper.eq(LabMaininfo::getSampleda, input.getLabMaininfo().getSampleda());
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getLabMaininfo().getRptGroup());
        queryWrapper.eq(LabMaininfo::getSampleNo, input.getLabMaininfo().getSampleNo());

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        Integer count = labMaininfos.size();
        //申请信息
        LabReqMain rmEntry = null;
        if (StringUtils.isNotEmpty(input.getReqNo())) {
            rmEntry = this.getLabReqMainEntity(input.getReqNo());
            if (rmEntry == null && StringUtils.isNotBlank(input.getReqNo())) {
                try {
                    AddLabMaininfo addLabMaininfo = new AddLabMaininfo();
                    addLabMaininfo.setReqNo(input.getReqNo());
                    Result apiReqMainInfo = this.getApiReqMainInfo(addLabMaininfo);
                    if ("400".equals(apiReqMainInfo.getStatus().get("code") + "")) {
                        throw new RuntimeException(apiReqMainInfo.getStatus().get("msg") + "");
                    }
                } catch (Exception e) {
                    throw e;
                }
                rmEntry = this.getLabReqMainEntity(input.getReqNo());
                if (rmEntry == null) {
                    throw new RuntimeException("未获取到申请信息！");
                }
            }
            //申请信息不为空判断报告单元下是否存在禁用申请项目
            String rptGroup = input.getRptGroup();
            String reqNo = rmEntry.getReqNo();
            boolean b = haveBanFeeItem(rptGroup, reqNo);
            if (b) {
                return Result.fail("该报告单元下存在禁用申请项目，不能上机！");
            }
        }

        /*验证系统参数，无条码号，禁止创建上机记录 2025-04-15 青岛优抚 王超提出需求，彭大jb分派*/
        SysParamParam sysp1111 = new SysParamParam();
        sysp1111.setParamCode("xtxxcs");
        sysp1111.setField("wtmhjzcjsjjl");
        List<SysParamFieldValueDto> r111 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1111);
        if (!r111.isEmpty()) {
            if ("1".equals(r111.get(0).getValue()) && StringUtils.isBlank(input.getReqNo())) {
                return Result.fail("无条码号禁止创建上机记录");
            }
        }

        if (count == 0) {
            input.getLabMaininfo().setTestTime(new Timestamp(System.currentTimeMillis()));
            SysUser sysUser = RedisUserManager.getUser();
            input.getLabMaininfo().setTestDoctor(sysUser.getUsername());
            input.getLabMaininfo().setOrgId(sysUser.getOrgId());
            if (BeanUtil.isEmpty(input.getLabMaininfo().getIsChk())) {
                input.getLabMaininfo().setIsChk(new BigDecimal(0));
            }

            if (!BeanUtil.isEmpty(rmEntry)) {
                BeanUtil.copyProperties(rmEntry, input.getLabMaininfo(), "id", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
            }

            //改修改
            LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabMaininfo::getSampleNo, input.getLabMaininfo().getSampleNo());
            lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, input.getLabMaininfo().getRptGroup());
            lambdaQueryWrapper.eq(LabMaininfo::getSampleda, input.getLabMaininfo().getSampleda());
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
            boolean b = labMaininfoService.saveOrUpdate(input.getLabMaininfo(), lambdaQueryWrapper);
            if (b) {
                new Thread(() -> {
                    labRptresultService.reCalcRptRssults(input.getLabMaininfo());
                }).start();

                //labRptresultCalcService.reCalcReferRange1(labMaininfo);

                //上机之后插入状态信息
                LabReqMain finalRmEntry = rmEntry;
                LabReqMain finalRmEntry1 = rmEntry;
                /*标本流程状态记录*/
                new Thread(() -> {
                    LabMainState reqState1 = new LabMainState();
                    reqState1.setMaininfoId(input.getLabMaininfo().getId());
                    reqState1.setStateCode("90");
                    reqState1.setStateValue("标本上机");
                    reqState1.setRemark("由" + sysUser.getRealname() + "创建检验记录");
                    labMainStateService.save(reqState1);
                    if (BeanUtil.isNotEmpty(finalRmEntry)) {
                        LabReqState reqState = new LabReqState();
                        reqState.setReqMainId(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getId() : "");
                        reqState.setSampleda(input.getLabMaininfo().getSampleda());
                        reqState.setSampleNo(input.getLabMaininfo().getSampleNo());
                        reqState.setRptGroup(input.getLabMaininfo().getRptGroup());
                        reqState.setReqNo(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
                        reqState.setStateCode("90");
                        reqState.setStateValue("标本上机");
                        reqState.setOrgId(finalRmEntry.getOrgId());
                        reqState.setCreator(sysUser.getId());
                        String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "检验上机,标本号:" + (BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
                        reqState.setRemark(rmk);
                        reqState.setSeq(labReqStateService.getMaxCount(finalRmEntry.getReqNo()));
                        labReqStateService.save(reqState);

                        if (BeanUtil.isNotEmpty(finalRmEntry1)) {
                            finalRmEntry1.setState("90");
                            finalRmEntry1.setStateNa("标本上机");
                            labReqMainService.saveOrUpdate(finalRmEntry1);
                        }
                    }
                }).start();

                return Result.succ(1, "插入数据成功", getMainInfoById(input.getLabMaininfo().getId()));
            } else {
                return Result.fail("插入数据失败！");
            }
        } else {
            if (!BeanUtil.isEmpty(rmEntry)) {
                if (!BeanUtil.isEmpty(rmEntry)) {

                    /*验证系统参数，东北双塔取消上机退费后2025-03-20，禁止上机*/
                    SysParamParam sysp0 = new SysParamParam();
                    sysp0.setParamCode("xtxxcs");
                    sysp0.setField("qxsjreturnfeenocheck");
                    List<SysParamFieldValueDto> r0 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp0);
                    if (!r0.isEmpty()) {
                        if (r0.get(0).getValue().equals("1") && "1".equals(rmEntry.getIsCancel() + "")) {
                            return Result.fail("已取消上机退费，无法再次上机");
                        }
                    }

                    try {
//                String reqState = labReqStateService.getReqState(reqMain.getId());
//                if (StringUtils.isNotEmpty(reqState)) {
//                    return Result.fail("当前标本已经作废");
//                }
                        if (!BeanUtil.isEmpty(rmEntry.getIsCancel()) && rmEntry.getIsCancel().equals(1)) {
                            return Result.fail("当前标本已经作废," + rmEntry.getCancelReason());
                        }
                    } catch (Exception ex) {
                        //TODO
                    }

                    /*验证系统参数，无签收时间，禁止上机*/
                    SysParamParam sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wqssjbbjzsj");
                    List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        if (r1.get(0).getValue().equals("1") && BeanUtil.isEmpty(rmEntry.getSignTime())) {
                            return Result.fail("无签收时间标本禁止上机");
                        }
                    }

                    //住院无签收时间标本禁止上机
                    /*验证系统参数，无签收时间，禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("zywqssjbbjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        if (r1.get(0).getValue().equals("1") && BeanUtil.isEmpty(rmEntry.getSignTime()) && !BeanUtil.isEmpty(rmEntry.getPatType()) && rmEntry.getPatType().equals("3")) {
                            return Result.fail("住院无签收时间标本禁止上机");
                        }
                    }

                    /*验证系统参数，无采样时间,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wcysjjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingTime())) {
                                return Result.fail("无采样时间禁止上机");
                            }
                        }
                    }

                    /*验证系统参数，无采样人,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wcyrjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingDoctor())) {
                                return Result.fail("无采样人禁止上机");
                            }
                        }
                    }

                    //---报告单元
                    /*验证系统参数，无采样时间,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("bgdyxtcs");
                    sysp1.setField("bgdywcysjjzsj");
                    sysp1.setClassifyCode(input.getRptGroup());

                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingTime())) {
                                return Result.fail("无采样时间禁止上机");
                            }
                        }
                    }
                    //---报告单元
                    /*验证系统参数，无采样人,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("bgdyxtcs");
                    sysp1.setField("bgdywcyrjzsj");
                    sysp1.setClassifyCode(input.getRptGroup());
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingDoctor())) {
                                return Result.fail("无采样人禁止上机");
                            }
                        }
                    }


                }


                /*有条码申请，检验记录无条码号，需要赋值 申请拷贝到检验记录*/
                if (StringUtils.isNotBlank(rmEntry.getReqNo()) && StringUtils.isBlank(input.getLabMaininfo().getReqNo())) {
                    BeanUtil.copyProperties(rmEntry, input.getLabMaininfo(), "id", "sampleNo", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
                }
                /*有条码申请，检验记录有条码号，但是条码号不相等，需要赋值 申请拷贝到检验记录*/
                if (StringUtils.isNotBlank(rmEntry.getReqNo()) && StringUtils.isNotBlank(input.getLabMaininfo().getReqNo()) && !rmEntry.getReqNo().equals(input.getLabMaininfo().getReqNo())) {
                    BeanUtil.copyProperties(rmEntry, input.getLabMaininfo(), "id", "sampleNo", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
                }

                //扫码上机时更新上机时间
                if(StringUtils.isNotEmpty(input.getReqNo()) && StringUtils.isEmpty(labMaininfos.get(0).getReqNo())){
                    input.getLabMaininfo().setTestTime(new Timestamp(new Date().getTime()));
                }

                SysUser sysUser = RedisUserManager.getUser();
                LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysInterface::getDelFlag, 0);
                wrapper.eq(SysInterface::getIsEnable, 1);
                wrapper.eq(SysInterface::getOrgId, rmEntry.getOrgId());
                List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                    /*发布报告相关*/
                    for (String webUrl : collect) {
                        //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                        /*添加系统参数判断是否需要重新获取计费信息*/
                        SysParamParam sysp111 = new SysParamParam();
                        sysp111.setParamCode("xtxxcs");
                        sysp111.setField("smsjsfxycxlqsq");
                        List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
                        if (!xtcs1.isEmpty()) {
                            if (xtcs1.get(0).getValue().equals("1")) {
                                Map<String, Object> updateMap = new HashMap<>();
                                updateMap.put("reqNo", rmEntry.getReqNo());
                                updateMap.put("username", sysUser.getUsername());
                                updateMap.put("realname", sysUser.getRealname());
                                updateMap.put("patType", rmEntry.getPatType());
                                updateMap.put("orgId", sysUser.getOrgId());
                                logger.info("开始执行上机计费接口:" + JSONUtil.toJsonStr(updateMap));
                                String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                                String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                                JSONObject jsonObject = new JSONObject(body);
                                JSONObject status = jsonObject.getJSONObject("status");
                                String code = status.get("code").toString();
                                if ("400".equals(code)) {
                                    return Result.fail(jsonObject.getStr("data"));
                                }
                            }
                        }
                    }
                }
            }
            int i = labMaininfoMapper.updateById(input.getLabMaininfo());
            if ((input.getLabMaininfo().getIsChk() == null || input.getLabMaininfo().getIsChk().intValue() < 2) && i > 0) {

                //插入模板数据
                TemplateParams tmpParam = new TemplateParams();
                tmpParam.setMaininfoId(input.getLabMaininfo().getId());
                tmpParam.setRptGroup(input.getLabMaininfo().getRptGroup());
                tmpParam.setSampleda(input.getLabMaininfo().getSampleda());
                tmpParam.setSampleNo(input.getLabMaininfo().getSampleNo());
                tmpParam.setReqNo(input.getLabMaininfo().getReqNo());
                labTemplateService.batchInsertDefItemDictAndTemplate(tmpParam);
                //重新计算检验结果
                //labRptresultCalcService.reCalcReferRange1(labMaininfo);
                new Thread(() -> {
                    labRptresultService.reCalcRptRssults(input.getLabMaininfo());
                }).start();

                return Result.succ(1, "修改据成功", getMainInfoById(input.getLabMaininfo().getId()));
            } else {
                return Result.succ(1, "修改据成功", getMainInfoById(input.getLabMaininfo().getId()));
            }
        }
    }

    public boolean haveBanFeeItem(String rptGroup, String reqNo){
        List<LabRptBanFeeitem> labRptBanFeeitems = labRptBanFeeitemMapper.selectList(new LambdaQueryWrapper<LabRptBanFeeitem>().eq(LabRptBanFeeitem::getRptGroup, rptGroup).eq(LabRptBanFeeitem::getDelFlag, 0));
        List<String> banFeeitems = labRptBanFeeitems.stream().map(LabRptBanFeeitem::getFeeCode).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<LabReqdetail> reqdetailList = labReqdetailService.list(new LambdaQueryWrapper<LabReqdetail>().eq(LabReqdetail::getReqNo, reqNo).eq(LabReqdetail::getDelFlag, 0));
        List<String> reqDetailFeeItems = reqdetailList.stream().map(LabReqdetail::getFeeCode).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //判断是否有禁止的项目
        if(CollectionUtil.isNotEmpty(banFeeitems)){
            Set<String> set1 = new HashSet<>(banFeeitems);
            return reqDetailFeeItems.stream().anyMatch(set1::contains);
        }
        return false;
    }

    /*批量打印报告*/
    public Result PrintRptBatch(List<LabMaininfo> labMaininfos) {
        if (labMaininfos.isEmpty()) {
            return Result.fail("没有要打印的数据");
        }
        List<String> ids = labMaininfos.stream().map(LabMaininfo::getId).collect(Collectors.toList());
        List<String> rptGroups = labMaininfos.stream().map(LabMaininfo::getRptGroup).collect(Collectors.toList());
        List<String> sampleNos = labMaininfos.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        List<Timestamp> sampledas = labMaininfos.stream().map(LabMaininfo::getSampleda).collect(Collectors.toList());


//        LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(LabRptmain::getDelFlag, 0);
//        queryWrapper.eq(LabRptmain::getIsFinalReport, 1);
//        queryWrapper.in(LabRptmain::getRptGroup, rptGroups);
//        queryWrapper.in(LabRptmain::getSampleNo, sampleNos);
//        queryWrapper.in(LabRptmain::getSampleda, sampledas);
//        List<LabRptmain> list = labRptmainMapper.selectList(queryWrapper);

        //根据三个主键in出了问题，修改了一下 2025-03-20
        List<LabRptmain> list =new ArrayList<>();
        for (LabMaininfo a : labMaininfos) {
            LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabRptmain::getDelFlag, 0);
            queryWrapper.eq(LabRptmain::getRptGroup, a.getRptGroup());
            queryWrapper.eq(LabRptmain::getSampleNo, a.getSampleNo());
            queryWrapper.eq(LabRptmain::getSampleda, a.getSampleda());
            queryWrapper.orderByDesc(LabRptmain::getCreateTime);
            List<LabRptmain> labRptmains1 = labRptmainMapper.selectList(queryWrapper);
            if(CollectionUtil.isEmpty(labRptmains1)){
                continue;
            }
            list.addAll(labRptmains1);
        }

        List<LabMaininfo> newRptmainRecs = new ArrayList<>();


        if (list.isEmpty()) {
            //全部生成报告记录
            newRptmainRecs = labMaininfos;
        } else {
            List<String> existIds = list.stream().map(LabRptmain::getMainInfoId).distinct().collect(Collectors.toList());

//            newRptmainRecs = labMaininfos.stream().filter(p -> !existIds.contains(p.getId())).collect(Collectors.toList());
            //修复一下审核后报告项目不准确的问题
            for (LabMaininfo labMaininfo : labMaininfos) {
                //1、报告不存在的加入进去
                if (!existIds.contains(labMaininfo.getId())) {
                    newRptmainRecs.add(labMaininfo);
                } else {
                    Optional<LabRptmain> first = list.stream().filter(p -> labMaininfo.getId().equals(p.getMainInfoId())).findFirst();
                    if (first.isPresent()) {
                        //2、报告数量不匹配的也加入进去
                        LabRptmain labRptmain = first.get();
                        LambdaQueryWrapper<LabRptdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(LabRptdetail::getRptMainCode, labRptmain.getId()).eq(LabRptdetail::getDelFlag, 0);
                        Integer detailCount = labRptdetailMapper.selectCount(lambdaQueryWrapper);
                        LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper1.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo()).eq(LabRptresult::getSampleda, labMaininfo.getSampleda()).eq(LabRptresult::getDelFlag, 0);
                        Integer resultCount = labRptresultMapper.selectCount(lambdaQueryWrapper1);
                        logger.info("报告项目数量不匹配，需要重新生成报告，检验主记录ID为：" + labRptmain.getMainInfoId());
                        if (detailCount != resultCount) {
                            newRptmainRecs.add(labMaininfo);
                        }
                    }
                }
            }
        }
        List<ReportPreviewDto> reportPreviewDtos = new ArrayList<>();
        if (newRptmainRecs.isEmpty()) {
            //labRptmains集合中如果mainInfoId重复取出现的第一条数据
            list = list.stream().collect(Collectors.groupingBy(item -> item.getMainInfoId() == null ? "__NULL__" : item.getMainInfoId(), LinkedHashMap::new, Collectors.toList())).values().stream().map(list1 -> list1.get(0)).collect(Collectors.toList());
            int i = 0;
            for (LabRptmain m : list) {
                ReportPreviewDto op = new ReportPreviewDto();
                op.setId(m.getId());
                op.setIsChecked(i == 0);
                op.setReportId(m.getRptTemplateCode());
                reportPreviewDtos.add(op);
                i++;
            }

            for (LabMaininfo m : labMaininfos) {
                String printDoctor = "";
                String printDoctorNa = "";
                try {
                    SysUser user = RedisUserManager.getUser();
                    printDoctor = user.getUsername();
                    printDoctorNa = user.getRealname();
                } catch (Exception e) {
                    printDoctor = m.getReqDoctor();
                    printDoctorNa = m.getReqDoctorNa();
                }

                m.setIsPrint(1);
                if (BeanUtil.isEmpty(m.getPrintCount())) {
                    m.setPrintCount(new BigDecimal(1));
                } else {
                    m.setPrintCount(m.getPrintCount().add(BigDecimal.ONE));
                }
                m.setPrintDoctor(printDoctor);
                m.setPrintDoctorNa(printDoctorNa);
                m.setPrintTime(new Timestamp(System.currentTimeMillis()));
            }

            labMaininfoService.updateBatchById(labMaininfos);
            //将reportPreviewDtos集合里面reportId去重 生成一个新集合
           /* List<ReportPreviewDto> reportPreviewDtos1 = reportPreviewDtos.stream().collect(Collectors.toMap(ReportPreviewDto::getReportId, Function.identity(), (existing, replacement) -> existing)).values().stream().collect(Collectors.toList());
            */
            return Result.succ(1, "", reportPreviewDtos);
        } else {
            if (StringUtils.isBlank(labMaininfos.get(0).getBacFlowNode())){
                for (LabMaininfo m : newRptmainRecs) {
                   // previewRpt(m, 2);
                }
            }
        }
        reportPreviewDtos = new ArrayList<>();
//       LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(LabRptmain::getDelFlag, 0);
//        queryWrapper.eq(LabRptmain::getIsFinalReport, 1);
////        queryWrapper.in(LabRptmain::getMainInfoId, ids);
//        queryWrapper.in(LabRptmain::getRptGroup, rptGroups);
//        queryWrapper.in(LabRptmain::getSampleNo, sampleNos);
//        queryWrapper.in(LabRptmain::getSampleda, sampledas);
//        queryWrapper.orderByDesc(LabRptmain::getCreateTime);

        //根据三个主键in出了问题，修改了一下 2025-03-20
        List<LabRptmain> list1 =new ArrayList<>();
        for (LabMaininfo a : labMaininfos) {
            LambdaQueryWrapper<LabRptmain> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(LabRptmain::getDelFlag, 0);
            queryWrapper1.eq(LabRptmain::getRptGroup, a.getRptGroup());
            queryWrapper1.eq(LabRptmain::getSampleNo, a.getSampleNo());
            queryWrapper1.eq(LabRptmain::getSampleda, a.getSampleda());
            queryWrapper1.orderByDesc(LabRptmain::getCreateTime);
            List<LabRptmain> labRptmains1 = labRptmainMapper.selectList(queryWrapper1);
            if(CollectionUtil.isEmpty(labRptmains1)){
                continue;
            }
            list1.addAll(labRptmains1);
        }
//labRptmains集合中如果mainInfoId重复取出现的第一条数据
        list1 = list1.stream().collect(Collectors.groupingBy(item -> item.getMainInfoId() == null ? "__NULL__" : item.getMainInfoId(), LinkedHashMap::new, Collectors.toList())).values().stream().map(lista -> lista.get(0)).collect(Collectors.toList());
        int i = 0;
        for (LabRptmain m : list1) {
            ReportPreviewDto op = new ReportPreviewDto();
            op.setId(m.getId());
            op.setIsChecked(i == 0);
            op.setReportId(m.getRptTemplateCode());
            reportPreviewDtos.add(op);
            i++;
        }
        for (LabMaininfo m : labMaininfos) {
            String printDoctor = "";
            String printDoctorNa = "";
            try {
                SysUser user = RedisUserManager.getUser();
                printDoctor = user.getUsername();
                printDoctorNa = user.getRealname();
            } catch (Exception e) {
                printDoctor = m.getReqDoctor();
                printDoctorNa = m.getReqDoctorNa();
            }
            m.setIsPrint(1);
            if (BeanUtil.isEmpty(m.getPrintCount())) {
                m.setPrintCount(new BigDecimal(1));
            } else {
                m.setPrintCount(m.getPrintCount().add(BigDecimal.ONE));
            }
            m.setPrintDoctor(printDoctor);
            m.setPrintDoctorNa(printDoctorNa);
            m.setPrintTime(new Timestamp(System.currentTimeMillis()));
        }

        labMaininfoService.updateBatchById(labMaininfos);
        //将reportPreviewDtos集合里面reportId去重 生成一个新集合
       /* List<ReportPreviewDto> reportPreviewDtos1 = reportPreviewDtos.stream().collect(Collectors.toMap(ReportPreviewDto::getReportId, Function.identity(), (existing, replacement) -> existing)).values().stream().collect(Collectors.toList());
        */
        return Result.succ(1, "", reportPreviewDtos);
    }

    public Result findResultReviewByPatNo(LabMaininfoParam param) {
        String jgbjyj = param.getJgbjyj();
        //根据病历号查询所有的申请信息
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class).leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabMaininfo::getDelFlag, 0)
//                .eq(LabMaininfo::getPatNo, param.getPatNo())
                .isNotNull(LabMaininfo::getRptGroup);
        queryWrapper.eq("0".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("1".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("3".equals(jgbjyj), LabMaininfo::getIdNo, param.getIdNo());
        if (StringUtils.isNotEmpty(param.getJgbjyqlb())) {
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(param.getJgbjyqlb().split(",")));
            list.add(param.getRptGroup());
            queryWrapper.in(LabMaininfo::getRptGroup, list);
        } else {
            queryWrapper.eq(LabMaininfo::getRptGroup, param.getRptGroup());
        }
        if (StringUtils.isNotEmpty(param.getJgbjjg())) {
            try {
                int day = Integer.parseInt(param.getJgbjjg());
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
            } catch (Exception e) {
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
            }
        } else {
            queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
        }
        queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(labMaininfos)) {
            return Result.succ(1, "数据处理成功", new ArrayList<>());
        }

        List<String> labminId = labMaininfos.stream().map(LabMaininfo::getId).distinct().collect(Collectors.toList());
        Boolean isDot = false;
        List<String> list2 = labminId.stream().filter(item -> !item.equals(param.getId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list2)) {
            isDot = true;
        }

        List<String> rptGroupIds = labMaininfos.stream().map(LabMaininfo::getRptGroup).distinct().collect(Collectors.toList());
        Map<String, List<LabMaininfo>> rptGroupMap = labMaininfos.stream().collect(Collectors.groupingBy(LabMaininfo::getRptGroup));

        /*查询出报告单元*/
        MPJLambdaWrapper<LabRptGroup> qRptGroupWrapper = new MPJLambdaWrapper<>();
        qRptGroupWrapper.eq(LabRptGroup::getDelFlag, 0);
        qRptGroupWrapper.in(LabRptGroup::getRptGroup, rptGroupIds);
        List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(qRptGroupWrapper);//.selectBatchIds(rptGroupIds);
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(labRptGroups)) {
            //遍历报告单元,动态插数据
            for (LabRptGroup labRptGroup : labRptGroups) {
                try {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("wtName", labRptGroup.getRptGroupName());
                    resultMap.put("isDot", isDot);
                    List<LabMaininfo> getMainInfoByGroupId = rptGroupMap.get(labRptGroup.getRptGroup());
                    List<String> maininfoIds = new ArrayList<>();

                    List<LabRptresult> labRptresults = new ArrayList<>();
                    for (LabMaininfo labMaininfo : getMainInfoByGroupId) {
                        MPJLambdaWrapper<LabRptresult> labRptResultQueryWrapper = new MPJLambdaWrapper<>();
                        labRptResultQueryWrapper.selectAll(LabRptresult.class);
                        labRptResultQueryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
                        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate = sdf.format(timestamp);
                        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                        Timestamp timestamp1 = new Timestamp(labMaininfo.getSampleda().getTime());
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate1 = sdf1.format(timestamp1);
                        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
                        labRptResultQueryWrapper.ge(LabRptresult::getSampleda, startTime);
                        labRptResultQueryWrapper.le(LabRptresult::getSampleda, endTime);
                        labRptResultQueryWrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
                        labRptResultQueryWrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                        labRptResultQueryWrapper.eq(LabRptresult::getDelFlag, 0);
                        labRptResultQueryWrapper.leftJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
                        labRptResultQueryWrapper.orderByAsc(LabRptresult::getDisplayOrder);
                        if (StringUtils.isNotEmpty(param.getJgbjjg())) {
                            try {
                                int day = Integer.parseInt(param.getJgbjjg());
                                labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
                            } catch (Exception e) {
                                labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
                            }
                        } else {
                            labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
                        }
                        queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
                        List<LabRptresult> labRptresult = labRptresultMapper.selectList(labRptResultQueryWrapper);
                        if (CollectionUtils.isNotEmpty(labRptresult)) {
                            labRptresult.forEach(item -> item.setMaininfoId(labMaininfo.getId()));
                            labRptresults.addAll(labRptresult);
                            maininfoIds.add(labMaininfo.getId());
                        }
                    }
                    labRptresults = labRptresults.stream().sorted(Comparator.comparing(item -> {
                                String displayOrder = item.getDisplayOrder();
                                if (displayOrder == null || displayOrder.trim().isEmpty()) {
                                    return Integer.MAX_VALUE; // 或者选择一个合适的默认值
                                }
                                try {
                                    return Integer.parseInt(displayOrder);
                                } catch (NumberFormatException e) {
                                    return Integer.MAX_VALUE; // 或者选择一个合适的默认值
                                }
                            }))
                            .collect(Collectors.toList());
                    Map<String, List<LabRptresult>> feeNamecollect = labRptresults.stream().collect(Collectors.groupingBy(LabRptresult::getItemNa));
                    List<String> feeNameList = labRptresults.stream().map(LabRptresult::getItemNa).distinct().collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(feeNameList)) {
                        continue;
                    }
                    List<Map<String, Object>> wlList = new ArrayList<>();
                    for (LabMaininfo labMaininfo : getMainInfoByGroupId) {
                        Map<String, Object> wls = new HashMap<>();
                        wls.put("id", labMaininfo.getId());
                        wls.put("wtName", labRptGroup.getRptGroupName());
                        wls.put("code", labMaininfo.getSampleNo());
                        wls.put("scheduleDate", labMaininfo.getSampleda());
                        wlList.add(wls);
                    }
                    List<Map<String, Object>> ansWithResults = new ArrayList<>();
                    //检验结果数据组装
                    for (String feeName : feeNameList) {
                        List<Map<String, Object>> wlResults = new ArrayList<>();
                        Map<String, Object> wtMap = new HashMap<>();
                        wtMap.put("name", feeName);
                        List<LabRptresult> labRptresults1 = feeNamecollect.get(feeName);
                        List<String> maininfoId = labRptresults1.stream().map(LabRptresult::getMaininfoId).distinct().collect(Collectors.toList());
                        List<String> subWlId = maininfoIds.stream().filter(item -> !maininfoId.contains(item)).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(subWlId)) {
                            for (String wId : subWlId) {
                                Map<String, Object> wlResult = new HashMap<>();
                                wlResult.put("wlId", wId);
                                wlResult.put("result", "");
                                wlResult.put("resultFlag", "");
                                wlResults.add(wlResult);
                            }
                        }
                        for (LabRptresult labRptresult : labRptresults1) {
                            Map<String, Object> wlResult = new HashMap<>();
                            wlResult.put("wlId", labRptresult.getMaininfoId());
                            wlResult.put("result", labRptresult.getTestResult());
                            wlResult.put("resultFlag", (StringUtils.isNotBlank(labRptresult.getResultFlag()) ? labRptresult.getResultFlag() : "M"));
                            wlResults.add(wlResult);
                        }
                        wtMap.put("wlResults", wlResults);
                        ansWithResults.add(wtMap);
                    }
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("ansWithResults", ansWithResults);
                    objectMap.put("wls", wlList);
                    resultMap.put("result", objectMap);
                    resultMapList.add(resultMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.succ(1, "数据处理成功", resultMapList);
    }


    public Result findResultReviewByPatNoArea(LabMaininfoParam param) {
        String jgbjyj = param.getJgbjyj();
        //根据病历号查询所有的申请信息
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class).leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabMaininfo::getDelFlag, 0)
//                .eq(LabMaininfo::getPatNo, param.getPatNo())
                .isNotNull(LabMaininfo::getRptGroup);
        queryWrapper.eq(LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq(LabMaininfo::getReqNo, param.getReqNo());
        if (StringUtils.isNotEmpty(param.getJgbjyqlb())) {
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(param.getJgbjyqlb().split(",")));
            list.add(param.getRptGroup());
            queryWrapper.in(LabMaininfo::getRptGroup, list);
        }
        if (StringUtils.isNotEmpty(param.getJgbjjg())) {
            try {
                int day = Integer.parseInt(param.getJgbjjg());
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
            } catch (Exception e) {
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
            }
        } else {
            queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
        }
        queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(labMaininfos)) {
            return Result.succ(1, "数据处理成功", new ArrayList<>());
        }

        List<String> labminId = labMaininfos.stream().map(LabMaininfo::getId).distinct().collect(Collectors.toList());
        Boolean isDot = false;
        List<String> list2 = labminId.stream().filter(item -> !item.equals(param.getId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list2)) {
            isDot = true;
        }

        List<String> rptGroupIds = labMaininfos.stream().map(LabMaininfo::getRptGroup).distinct().collect(Collectors.toList());
        Map<String, List<LabMaininfo>> rptGroupMap = labMaininfos.stream().collect(Collectors.groupingBy(LabMaininfo::getRptGroup));

        /*查询出报告单元*/
        MPJLambdaWrapper<LabRptGroup> qRptGroupWrapper = new MPJLambdaWrapper<>();
        qRptGroupWrapper.eq(LabRptGroup::getDelFlag, 0);
        qRptGroupWrapper.in(LabRptGroup::getRptGroup, rptGroupIds);
        List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(qRptGroupWrapper);//.selectBatchIds(rptGroupIds);
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(labRptGroups)) {
            //遍历报告单元,动态插数据
            for (LabRptGroup labRptGroup : labRptGroups) {
                try {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("wtName", labRptGroup.getRptGroupName());
                    resultMap.put("isDot", isDot);
                    List<LabMaininfo> getMainInfoByGroupId = rptGroupMap.get(labRptGroup.getRptGroup());
                    List<String> maininfoIds = new ArrayList<>();

                    List<LabRptresult> labRptresults = new ArrayList<>();

                    ExecutorService executorService = Executors.newFixedThreadPool(getMainInfoByGroupId.size()); // 创建一个线程池
                    CountDownLatch countDownLatch = new CountDownLatch(getMainInfoByGroupId.size());

                    for (LabMaininfo labMaininfo : getMainInfoByGroupId) {
                        List<LabRptresult> finalLabRptresults = labRptresults;
                        Future<?> future = executorService.submit(() -> {
                            //报告项目
                            try {
                                MPJLambdaWrapper<LabRptresult> labRptResultQueryWrapper = new MPJLambdaWrapper<>();
                                labRptResultQueryWrapper.selectAll(LabRptresult.class);
                                labRptResultQueryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
                                Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String formattedDate = sdf.format(timestamp);
                                Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                                Timestamp timestamp1 = new Timestamp(labMaininfo.getSampleda().getTime());
                                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                                String formattedDate1 = sdf1.format(timestamp1);
                                Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
                                labRptResultQueryWrapper.ge(LabRptresult::getSampleda, startTime);
                                labRptResultQueryWrapper.le(LabRptresult::getSampleda, endTime);
                                labRptResultQueryWrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
                                labRptResultQueryWrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                                labRptResultQueryWrapper.eq(LabRptresult::getDelFlag, 0);
                                labRptResultQueryWrapper.leftJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
                                labRptResultQueryWrapper.orderByAsc(LabRptresult::getDisplayOrder);
                                if (StringUtils.isNotEmpty(param.getJgbjjg())) {
                                    try {
                                        int day = Integer.parseInt(param.getJgbjjg());
                                        labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
                                    } catch (Exception e) {
                                        labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
                                    }
                                } else {
                                    labRptResultQueryWrapper.gt(LabRptresult::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
                                }
                                queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
                                List<LabRptresult> labRptresult = labRptresultMapper.selectList(labRptResultQueryWrapper);
                                if (CollectionUtils.isNotEmpty(labRptresult)) {
                                    labRptresult.forEach(item -> item.setMaininfoId(labMaininfo.getId()));
                                    finalLabRptresults.addAll(labRptresult);
                                    maininfoIds.add(labMaininfo.getId());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                countDownLatch.countDown();
                            }
                        });
                        labRptresults.addAll(finalLabRptresults);
                    }

                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    executorService.shutdown(); // 关闭线程池


                    labRptresults = labRptresults.stream().sorted(Comparator.comparing(item -> Optional.ofNullable(item.getDisplayOrder()).map(Integer::parseInt).orElse(Integer.MAX_VALUE))) // 或者选择一个合适的默认值
                            .collect(Collectors.toList());
                    Map<String, List<LabRptresult>> feeNamecollect = labRptresults.stream().collect(Collectors.groupingBy(LabRptresult::getItemNa));
                    List<String> feeNameList = labRptresults.stream().map(LabRptresult::getItemNa).distinct().collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(feeNameList)) {
                        continue;
                    }
                    List<Map<String, Object>> wlList = new ArrayList<>();
                    for (LabMaininfo labMaininfo : getMainInfoByGroupId) {
                        Map<String, Object> wls = new HashMap<>();
                        wls.put("id", labMaininfo.getId());
                        wls.put("wtName", labRptGroup.getRptGroupName());
                        wls.put("code", labMaininfo.getSampleNo());
                        wls.put("scheduleDate", labMaininfo.getSampleda());
                        wlList.add(wls);
                    }
                    List<Map<String, Object>> ansWithResults = new ArrayList<>();
                    //检验结果数据组装
                    for (String feeName : feeNameList) {
                        List<Map<String, Object>> wlResults = new ArrayList<>();
                        Map<String, Object> wtMap = new HashMap<>();
                        wtMap.put("name", feeName);
                        List<LabRptresult> labRptresults1 = feeNamecollect.get(feeName);
                        List<String> maininfoId = labRptresults1.stream().map(LabRptresult::getMaininfoId).distinct().collect(Collectors.toList());
                        List<String> subWlId = maininfoIds.stream().filter(item -> !maininfoId.contains(item)).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(subWlId)) {
                            for (String wId : subWlId) {
                                Map<String, Object> wlResult = new HashMap<>();
                                wlResult.put("wlId", wId);
                                wlResult.put("result", "");
                                wlResult.put("resultFlag", "");
                                wlResults.add(wlResult);
                            }
                        }
                        for (LabRptresult labRptresult : labRptresults1) {
                            Map<String, Object> wlResult = new HashMap<>();
                            wlResult.put("wlId", labRptresult.getMaininfoId());
                            wlResult.put("result", labRptresult.getTestResult());
                            wlResult.put("resultFlag", (StringUtils.isNotBlank(labRptresult.getResultFlag()) ? labRptresult.getResultFlag() : "M"));
                            wlResults.add(wlResult);
                        }
                        wtMap.put("wlResults", wlResults);
                        ansWithResults.add(wtMap);
                    }
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("ansWithResults", ansWithResults);
                    objectMap.put("wls", wlList);
                    resultMap.put("result", objectMap);
                    resultMapList.add(resultMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.succ(1, "数据处理成功", resultMapList);
    }


    public Result findResultReviewHistory(LabMaininfoParam param) {
        String jgbjyj = param.getJgbjyj();
        //根据病历号查询所有的申请信息
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class).leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabMaininfo::getDelFlag, 0)
//                .eq(LabMaininfo::getPatNo, param.getPatNo())
                .isNotNull(LabMaininfo::getRptGroup);
        queryWrapper.eq("0".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("1".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("3".equals(jgbjyj), LabMaininfo::getIdNo, param.getIdNo());
        if (StringUtils.isNotEmpty(param.getJgbjyqlb())) {
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(param.getJgbjyqlb().split(",")));
            list.add(param.getRptGroup());
            queryWrapper.in(LabMaininfo::getRptGroup, list);
        } else {
            queryWrapper.eq(LabMaininfo::getRptGroup, param.getRptGroup());
        }
        if (StringUtils.isNotEmpty(param.getJgbjjg())) {
            try {
                int day = Integer.parseInt(param.getJgbjjg());
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
            } catch (Exception e) {
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
            }
        } else {
            queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
        }
        queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        if (labMaininfos.size() > 1) {
            return Result.succ(1, "数据处理成功", 1);
        } else {
            return Result.succ(1, "数据处理成功", 0);
        }
    }

    public Result findResultRptReviewHistory(LabMaininfoParam param) {
        String jgbjyj = param.getJgbjyj();
        //根据病历号查询所有的申请信息
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class).leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabMaininfo::getDelFlag, 0)
//                .eq(LabMaininfo::getPatNo, param.getPatNo())
                .isNotNull(LabMaininfo::getRptGroup);
        queryWrapper.eq("0".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("1".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNa, param.getPatNa());
        queryWrapper.eq("2".equals(jgbjyj), LabMaininfo::getPatNo, param.getPatNo());
        queryWrapper.eq("3".equals(jgbjyj), LabMaininfo::getIdNo, param.getIdNo());
        if (StringUtils.isNotEmpty(param.getJgbjyqlb())) {
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(param.getJgbjyqlb().split(",")));
            list.add(param.getRptGroup());
            queryWrapper.in(LabMaininfo::getRptGroup, list);
        } else {
            queryWrapper.eq(LabMaininfo::getRptGroup, param.getRptGroup());
        }
        if (StringUtils.isNotEmpty(param.getJgbjjg())) {
            try {
                int day = Integer.parseInt(param.getJgbjjg());
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -day));
            } catch (Exception e) {
                queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
            }
        } else {
            queryWrapper.gt(LabMaininfo::getSampleda, DateUtil.offsetDay(DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"), -360));
        }
        queryWrapper.le(LabMaininfo::getSampleda, DateUtil.parse(param.getSampleda(), "yyyy-MM-dd"));
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        if (labMaininfos.size() > 1) {
            return Result.succ(1, "数据处理成功", 1);
        } else {
            return Result.succ(1, "数据处理成功", 0);
        }
    }


    /*批量预览报告*/
    public Result ViewRptBatch(List<LabMaininfo> labMaininfos) {
        if (labMaininfos.isEmpty()) {
            return Result.fail("没有要预览的数据");
        }
        List<String> ids = labMaininfos.stream().map(LabMaininfo::getId).collect(Collectors.toList());
        List<String> rptGroups = labMaininfos.stream().map(LabMaininfo::getRptGroup).collect(Collectors.toList());
        List<String> sampleNos = labMaininfos.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        List<Timestamp> sampledas = labMaininfos.stream().map(LabMaininfo::getSampleda).collect(Collectors.toList());
        List<LabMaininfo> wshList = labMaininfos.stream().filter(a -> (a.getIsChk() == null || a.getIsChk().intValue() < 1)).collect(Collectors.toList());
        //已审核的判断数量是否一致
        for (LabMaininfo labMaininfo : labMaininfos) {
            //2、报告数量不匹配的也加入进去
            LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo()).eq(LabRptmain::getSampleda, labMaininfo.getSampleda());
            lambdaQueryWrapper.eq(LabRptmain::getDelFlag, 0);
            List<LabRptmain> labRptmains = labRptmainMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtil.isEmpty(labRptmains)){
                continue;
            }
            LabRptmain labRptmain = labRptmains.get(0);
            LambdaQueryWrapper<LabRptdetail> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(LabRptdetail::getRptMainCode, labRptmain.getId()).eq(LabRptdetail::getDelFlag, 0);
            Integer detailCount = labRptdetailMapper.selectCount(lambdaQueryWrapper1);
            LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo()).eq(LabRptresult::getSampleda, labMaininfo.getSampleda()).eq(LabRptresult::getDelFlag, 0);
            Integer resultCount = labRptresultMapper.selectCount(lambdaQueryWrapper2);
            logger.info("报告项目数量不匹配，需要重新生成报告，检验主记录ID为：" + labRptmain.getMainInfoId());
            if (detailCount != resultCount) {
                wshList.add(labMaininfo);
            }
        }
        if (CollectionUtils.isNotEmpty(wshList) && StringUtils.isBlank(labMaininfos.get(0).getBacFlowNode())) {
            wshList.forEach(a -> {
               // previewRpt(a, 2);
            });
        }
        //根据三个主键in出了问题，修改了一下 2025-03-20
        List<ReportPreviewDto> reportPreviewDtos = new ArrayList<>();
        List<LabRptmain> labRptmains =new ArrayList<>();
        for (LabMaininfo labMaininfo : labMaininfos) {
            LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabRptmain::getDelFlag, 0);
            queryWrapper.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup());
            queryWrapper.eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo());
            queryWrapper.eq(LabRptmain::getSampleda, labMaininfo.getSampleda());
            queryWrapper.orderByDesc(LabRptmain::getCreateTime);
            List<LabRptmain> labRptmains1 = labRptmainMapper.selectList(queryWrapper);
            if (CollectionUtil.isEmpty(labRptmains1)){
                continue;
            }
            labRptmains.addAll(labRptmains1);
        }
        //labRptmains集合中如果mainInfoId重复取出现的第一条数据

        labRptmains = labRptmains.stream().collect(Collectors.groupingBy(item -> item.getMainInfoId() == null ? "__NULL__" : item.getMainInfoId(), LinkedHashMap::new, Collectors.toList())).values().stream().map(list -> list.get(0)).collect(Collectors.toList());
        int i = 0;
        for (LabRptmain m : labRptmains) {
            ReportPreviewDto op = new ReportPreviewDto();
            op.setId(m.getId());
            op.setIsChecked(i == 0);
            op.setReportId(m.getRptTemplateCode());
            PubReport byId = pubReportService.getById(m.getRptTemplateCode());
            op.setReportTemplateName(byId == null ? "" : byId.getName());
            reportPreviewDtos.add(op);
            i++;
        }
        //将reportPreviewDtos集合里面reportId去重 生成一个新集合
        /*List<ReportPreviewDto> reportPreviewDtos1 = reportPreviewDtos.stream().collect(Collectors.toMap(ReportPreviewDto::getReportId, Function.identity(), (existing, replacement) -> existing)).values().stream().collect(Collectors.toList());
        */
        return Result.succ(1, "", reportPreviewDtos);
    }


    public Result labMainInfoMergePrint(BatchPrintDto batchPrintDto) throws JsonProcessingException {
        if (CollectionUtils.isEmpty(batchPrintDto.getLabMaininfoIds())) {
            return Result.fail("请选择要合并的记录");
        }
        MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabMaininfo.class);
        lambdaQueryWrapper.selectAs(LabReqMainQuery::getPatId, BatchPrintVo::getPatId);
        lambdaQueryWrapper.in(LabMaininfo::getId, batchPrintDto.getLabMaininfoIds());
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        lambdaQueryWrapper.leftJoin(LabReqMainQuery.class, LabReqMainQuery::getReqNo, LabMaininfo::getReqNo);
        List<BatchPrintVo> batchPrintVos = labMaininfoMapper.selectJoinList(BatchPrintVo.class, lambdaQueryWrapper);
        List<String> collect = batchPrintVos.stream().map(item -> (StringUtils.isBlank(item.getPatNo()) ? "" : item.getPatNo()) + (StringUtils.isBlank(item.getPatId()) ? "" : item.getPatId()) + (StringUtils.isBlank(item.getReqDept()) ? "" : item.getReqDept())).distinct().collect(Collectors.toList());
        if (collect.size() > 1) {
            return Result.fail("非同一个就诊科室或非同一个病人不允许合并打印");
        }
        if (collect.size() <= 0) {
            return Result.fail("请选择要合并的记录");
        }

        List<LabMaininfo> listChk = batchPrintVos.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) < 0)).collect(Collectors.toList());
        /*验证系统参数，山亭未审核可以打印镜检报告*/
        Boolean jjbgIsShow=false;
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("hisckbgwshsfdyjjbg");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty()) {
            if (r1.get(0).getValue().equals("1")) {
                jjbgIsShow=true;
            }
        }
        if (!listChk.isEmpty()&&!jjbgIsShow) {
            return Result.fail("号段中存在未审核的数据");
        }

        List<LabMaininfo> listLock = batchPrintVos.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());

        if (!listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }
        List<LabMaininfo> labMaininfos = new ArrayList<>(batchPrintVos);
        /*打印人*/
        //SysUser sysUser = RedisUserManager.getUser();

        for (LabMaininfo item : labMaininfos) {
            item.setIsPrint(1);
            //item.setPrintDoctor(sysUser.getUsername());
            item.setPrintTime(new Timestamp(System.currentTimeMillis()));
            if (BeanUtil.isEmpty(item.getPrintCount())) {
                item.setPrintCount(new BigDecimal(0));
            } else {
                item.setPrintCount(item.getPrintCount().add(BigDecimal.ONE));
            }
        }

        boolean r = labMaininfoService.updateBatchById(labMaininfos);

        List<LabRptmain> list=new ArrayList<>();
        for (LabMaininfo a : labMaininfos) {
            LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabRptmain::getDelFlag, 0);
            queryWrapper.eq(LabRptmain::getRptGroup, a.getRptGroup());
            queryWrapper.eq(LabRptmain::getSampleNo, a.getSampleNo());
            queryWrapper.eq(LabRptmain::getSampleda, a.getSampleda());
            queryWrapper.orderByDesc(LabRptmain::getCreateTime);
            List<LabRptmain> labRptmains1 = labRptmainMapper.selectList(queryWrapper);
            list.addAll(labRptmains1);
        }
        //labRptmains集合中如果mainInfoId重复取出现的第一条数据
        list = list.stream().collect(Collectors.groupingBy(item -> item.getMainInfoId() == null ? "__NULL__" : item.getMainInfoId(), LinkedHashMap::new, Collectors.toList())).values().stream().map(lista -> lista.get(0)).collect(Collectors.toList());
       /* List<LabRptmain> reportPreviewDtos1 = labRptmainList.stream().collect(Collectors.toMap(LabRptmain::getRptTemplateCode, Function.identity(), (existing, replacement) -> existing)).values().stream().collect(Collectors.toList());
*/
        return Result.succ(1, "合并打印成功", list);
    }

    /*获取单个标本号*/
    private List<String> GetAimCode(String code) {
        List<String> codes = new ArrayList<>();

        code = code.replace("，", ",");
        code = code.replace("—", "-");

        String[] codeArray = code.split(",");

        for (String c : codeArray) {
            if (!c.contains("-")) {
                codes.add(c);
            } else {
                String[] arr = code.split("-");
                for (int i = Integer.parseInt(arr[0]); i <= Integer.parseInt(arr[1]); i++) {
                    codes.add(i + "");
                }
            }
        }
        return codes;
    }

    /**
     * 同步his
     */
    public void his(List<LabMaininfo> labMaininfo) {
        //同步HIS,只有审核时 才同步报告到HIS
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, labMaininfo.get(0).getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //删除报告
        SysUser sysUser = RedisUserManager.getUser();
        if (CollectionUtils.isNotEmpty(collect)) {
            try {
                /*发布报告相关*/
                for (String webUrl : collect) {

                    String url = webUrl + "/public/chkbatch";
                    Map<String, Object> map = new HashMap<>();
                    map.put("list", labMaininfo);

                    /*---------------------*/
                    // 发送请求
                    String s = HttpUtil.createPost(url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(map)).contentType("application/json").execute().body();
                    /*---------------------*/
                    labMaininfo.forEach(labMaininfo1 -> {
//                        new Thread(() -> {
                        MPJLambdaWrapper<LabRptresult> rptresulWrapper = new MPJLambdaWrapper<>();
                        rptresulWrapper.selectAll(LabRptresult.class);
                        rptresulWrapper.selectAs("itmdict", LabItemDict::getUnit, LabRptresult::getItemUnit);
                        rptresulWrapper.eq(LabRptresult::getSampleNo, labMaininfo1.getSampleNo());
                        rptresulWrapper.eq(LabRptresult::getRptGroup, labMaininfo1.getRptGroup());
                        Timestamp startTime = Timestamp.valueOf(labMaininfo1.getSampleda().toString().substring(0, 10) + " 00:00:00");
                        Timestamp endTime = Timestamp.valueOf(labMaininfo1.getSampleda().toString().substring(0, 10) + " 23:59:59");
                        rptresulWrapper.ge(LabRptresult::getSampleda, startTime);
                        rptresulWrapper.le(LabRptresult::getSampleda, endTime);
                        rptresulWrapper.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
                        rptresulWrapper.eq(LabRptresult::getDelFlag, 0);
                        rptresulWrapper.orderByAsc(LabItemDict::getSeq);
                        List<LabRptresult> labRptresults = labRptresultMapper.selectList(rptresulWrapper);
                        if (CollectionUtils.isNotEmpty(labRptresults)) {
                            List<Map> list = new ArrayList<>();
                            Map<String, Object> releaseReportMap = new HashMap<>();
                            String releaseReport = webUrl + "/public/releaseReport";
                            for (LabRptresult labRptresult : labRptresults) {
                                HashMap<Object, Object> map1 = new HashMap<>();
                                map1.put("itemNo", labRptresult.getItemNo());
                                map1.put("itemNa", labRptresult.getItemNa());
                                map1.put("unit", labRptresult.getItemUnit());
                                map1.put("testResult", labRptresult.getTestResult());
                                map1.put("resultFlag", labRptresult.getResultFlag());
                                map1.put("ref", StringUtils.isBlank(labRptresult.getRef()) ? "" : labRptresult.getRef());
                                map1.put("rptGroup", labRptresult.getRptGroup());
                                map1.put("id", UUID.randomUUID().toString());
                                map1.put("sampleNo", labMaininfo1.getSampleNo());
                                map1.put("reqNo", labMaininfo1.getReqNo());
                                map1.put("testDoctor", labMaininfo1.getTestDoctor());
                                map1.put("chkDoctor", labMaininfo1.getChkDoctor());
                                map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo1.getSampleda()));
                                list.add(map1);
                            }
                            releaseReportMap.put("orgId", labMaininfo1.getOrgId());
                            releaseReportMap.put("reportInfos", list);
                            releaseReportMap.put("username", sysUser.getUsername());
                            releaseReportMap.put("realname", sysUser.getRealname());
                            String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                            //HttpUtils.doPost(releaseReport, JSONUtils.map2json(releaseReportMap));
                            logger.info("发布报告返回值:\n" + release);
                            JSONObject releaseObject = new JSONObject(release);
                            JSONObject releaseStatus = releaseObject.getJSONObject("status");
                            String releaseCode = releaseStatus.get("code").toString();
                            if (!"400".equals(releaseCode)) {
                                //走存储过程修改
                                String updateUrl = webUrl + "/public/updateReportStatus";
                                Map<String, Object> updateMap = new HashMap<>();
                                updateMap.put("status", "0306");//审核
                                updateMap.put("reqNo", labMaininfo1.getReqNo());
                                updateMap.put("patType", labMaininfo1.getPatType());
                                updateMap.put("chkDoctor", labMaininfo1.getChkDoctor());
                                updateMap.put("testDoctor", labMaininfo1.getTestDoctor());
                                updateMap.put("patType", labMaininfo1.getPatType());
                                updateMap.put("samplingTime", BeanUtil.isEmpty(labMaininfo1.getSamplingTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo1.getSamplingTime()));
                                updateMap.put("signTime", BeanUtil.isEmpty(labMaininfo1.getSignTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo1.getSignTime()));
                                updateMap.put("operateTime", BeanUtil.isEmpty(labMaininfo1.getTestTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo1.getTestTime()));
                                updateMap.put("reportTime", BeanUtil.isEmpty(labMaininfo1.getChkTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo1.getChkTime()));
                                updateMap.put("orgId", labMaininfo1.getOrgId());
                                updateMap.put("username", sysUser.getUsername());
                                updateMap.put("realname", sysUser.getRealname());
                                updateMap.put("id", labMaininfo1.getId());
                                String update = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                                logger.info("更新状态返回值:\n" + update);
                            }
                        }
//                        }).start();
                    });
                    //新增报告
//                    JSONObject jsonObject = new JSONObject(s);
//                    JSONObject status = jsonObject.getJSONObject("status");
//                    String msg = status.get("msg").toString();
//                    String code = status.get("code").toString();
//                    if ("400".equals(code)) {
//                        throw new RuntimeException("接口管理平台异常,请检查");
//                    }
                }
                /*回写过渡板Limp相关，放到线程中，以免影响审核速度，如果同步失败，取消审核，再次审核还会同步一遍*/

/*                new Thread(() -> {
                    for (String webUrl : collect) {
                        for (LabMaininfo maininfo : labMaininfo) {
                            String url = webUrl + "/public/labMaininfoChk";
//                            String s = HttpUtils.doPost(url, JSONUtils.object2json(finalLabMaininfo));
                            String body = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(maininfo)).contentType("application/json").execute().body();
                        }

                    }
                }).start();*/
            } catch (Exception e) {
                throw new RuntimeException("接口管理平台异常,请检查");
            }

        }

    }

    public Result findRptResultByLabMaininfoMouted(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.succ(1, "id为空", "");
        }
        LambdaQueryWrapper<LabMaininfo> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfo::getDelFlag, 0);
        queryMI.eq(LabMaininfo::getId, id);
        LabMaininfo miEntry = labMaininfoMapper.selectOne(queryMI);
        if (BeanUtil.isEmpty(miEntry)) {
            return Result.succ(1, "查无上机记录", "");
        }

        MPJLambdaWrapper<LabRptresult> queryWrapper = new MPJLambdaWrapper<>();
        //queryWrapper.eq(LabRptresult::getDelFlag, 0).eq(LabRptresult::getMaininfoId, id);
        //queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.distinct().selectAll(LabRptresult.class);
        queryWrapper.selectAs("instr", LabInstrSetup::getInstrName, LabRptresult::getInstrNa);
        queryWrapper.selectAs("dict", LabItemDict::getUnit, LabRptresult::getItemUnit);
        queryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
        queryWrapper.selectAs("dict", LabItemDict::getIsCalcItem, LabRptresult::getIsCalcItem);
        queryWrapper.selectAs("dict", LabItemDict::getId, LabRptresult::getItemDictId);
        queryWrapper.leftJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        queryWrapper.leftJoin(LabInstrSetup.class, "instr", p -> p.eq(LabInstrSetup::getRptGroup, LabRptresult::getRptGroup).eq(LabInstrSetup::getInstrCode, LabRptresult::getInstrCode).eq(LabInstrSetup::getDelFlag, 0));
        queryWrapper.eq(LabRptresult::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp timestamp1 = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
        queryWrapper.ge(LabRptresult::getSampleda, startTime);
        queryWrapper.le(LabRptresult::getSampleda, endTime);
        queryWrapper.eq(LabRptresult::getRptGroup, miEntry.getRptGroup());
        queryWrapper.eq(LabRptresult::getSampleNo, miEntry.getSampleNo());
        queryWrapper.orderByAsc(LabRptresult::getDisplayOrder);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);

        if (!labRptresults.isEmpty()) {
            List<LabRptresult> collect = labRptresults.stream().filter(a -> StringUtils.isBlank(a.getMaininfoId())).collect(Collectors.toList());
            for (LabRptresult m : collect) {
                m.setMaininfoId(miEntry.getId());
            }
            labRptresultService.updateBatchById(collect);
        }

        //系统参数设置
        SysParamParam bzdscwjgtm = new SysParamParam();
        /*不自动删除无结果项目 bzdscwjgxm*/
        bzdscwjgtm = new SysParamParam();
        bzdscwjgtm.setParamCode("bgdyxtcs");
        bzdscwjgtm.setField("bzdscwjgxm");
        bzdscwjgtm.setClassifyCode(miEntry.getRptGroup());
        List<SysParamFieldValueDto> kcflrdstndtmLst = null;
        try {
            kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(bzdscwjgtm);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isNotEmpty(kcflrdstndtmLst)) {
            String bzdscwjgxm = kcflrdstndtmLst.get(0).getValue();
            if ("1".equals(bzdscwjgxm)) {
                List<String> collect = labRptresults.stream().filter(p -> StringUtils.isEmpty(p.getTestResult())).map(LabRptresult::getId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    labRptresultService.removeByIds(collect);
                    labRptresults = labRptresults.stream().filter(s -> !collect.contains(s.getId())).collect(Collectors.toList());
                }
            }
        }

        List<String> list = labRptresults.stream().map(p -> p.getItemNo()).collect(Collectors.toList());

        if (list.size() >0){
            List<LabFeeitemVsItemDict> labFeeitemVsItemDicts = labFeeitemVsItemDictMapper.selectList(
                    new LambdaQueryWrapper<LabFeeitemVsItemDict>().in(LabFeeitemVsItemDict::getItemNo, list)
                            .eq(LabFeeitemVsItemDict::getRptGroup, miEntry.getRptGroup()).eq(LabFeeitemVsItemDict::getDelFlag, 0));
            for (LabRptresult rptresult : labRptresults) {
                if (rptresult.getIsCalcItem() != null && rptresult.getIsCalcItem() == 1) {
                    rptresult.setIsContrast(1);
                    continue;
                }
                LabFeeitemVsItemDict labFeeitemVsItemDict = labFeeitemVsItemDicts.stream().filter(a -> a.getItemNo().equals(rptresult.getItemNo())).findFirst().orElse(null);
                if (labFeeitemVsItemDict != null) {
                    rptresult.setIsContrast(1);
                } else {
                    rptresult.setIsContrast(0);
                }
            }
        }
        
        return Result.succ(1, "查询结果成功", labRptresults);
    }

    public Result judgeStainingResult(LabMaininfoParam labMaininfo) {
        MPJLambdaWrapper<LabFeeItem> feeItemWrapper = new MPJLambdaWrapper<>();
        feeItemWrapper.selectAll(LabFeeItem.class);
        feeItemWrapper.leftJoin(LabReqdetail.class, "ld", eq -> eq.eq(LabReqdetail::getDelFlag, 0).eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode).eq(LabReqdetail::getReqNo, labMaininfo.getReqNo()));
        feeItemWrapper.eq(LabFeeItem::getDelFlag, 0);
        feeItemWrapper.eq(LabFeeItem::getIsStaining, "1");
        List<LabFeeItem> feeItemList = labFeeItemService.list(feeItemWrapper);
        if (CollectionUtil.isNotEmpty(feeItemList)) {
            List<BacStainingResult> stainingResults = bacStainingResultService.list(new LambdaQueryWrapper<BacStainingResult>().eq(BacStainingResult::getRptGroup, labMaininfo.getRptGroup()).eq(BacStainingResult::getSampleNo, labMaininfo.getSampleNo()).eq(BacStainingResult::getSampleda, labMaininfo.getSampleda()).isNull(BacStainingResult::getStrainNo).eq(BacStainingResult::getDelFlag, 0));
            if (CollectionUtil.isNotEmpty(stainingResults)) {
                return Result.succ(true);
            } else {
                return Result.succ(false);
            }
        } else {
            return Result.succ(true);
        }
    }

    private List<String> getListValueMethod(String value) {
        // 去掉首尾的方括号
        String str = value.replaceAll("\\[|\\]", "");
        // 分割字符串
        String[] parts = str.split(",");
        // 创建一个列表来存储整数
        List<String> list = new ArrayList<>();
        // 遍历分割后的字符串数组，并将其转换为整数后添加到列表中
        for (String part : parts) {
            // 去掉引号
            String numStr = part.trim().replaceAll("\"", "");
            list.add(numStr);
        }
        return list;
    }
}
